text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/storage_impl/src/tokenization.rs // Module: storage_impl::src::tokenization #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use diesel_models::tokenization as tokenization_diesel; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use error_stack::{report, ResultExt}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; use super::MockDb; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use crate::{connection, errors}; use crate::{kv_router_store::KVRouterStore, DatabaseStore, RouterStore}; #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] pub trait TokenizationInterface {} #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub trait TokenizationInterface { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; async fn update_tokenization_record( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; tokenization .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let tokenization = tokenization_diesel::Tokenization::find_by_id(&conn, token) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let domain = tokenization .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok(domain) } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let tokenization_record = Conversion::convert(tokenization_record) .await .change_context(errors::StorageError::DecryptionError)?; self.call_database( key_manager_state, merchant_key_store, tokenization_record.update_with_id( &conn, tokenization_diesel::TokenizationUpdateInternal::from(tokenization_update), ), ) .await } } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> { async fn insert_tokenization( &self, tokenization: hyperswitch_domain_models::tokenization::Tokenization, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .insert_tokenization(tokenization, merchant_key_store, key_manager_state) .await } async fn get_entity_id_vault_id_by_token_id( &self, token: &common_utils::id_type::GlobalTokenId, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state) .await } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { self.router_store .update_tokenization_record( tokenization_record, tokenization_update, merchant_key_store, key_manager_state, ) .await } } #[async_trait::async_trait] #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl TokenizationInterface for MockDb { async fn insert_tokenization( &self, _tokenization: hyperswitch_domain_models::tokenization::Tokenization, _merchant_key_store: &MerchantKeyStore, _key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn get_entity_id_vault_id_by_token_id( &self, _token: &common_utils::id_type::GlobalTokenId, _merchant_key_store: &MerchantKeyStore, _key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_tokenization_record( &self, tokenization_record: hyperswitch_domain_models::tokenization::Tokenization, tokenization_update: hyperswitch_domain_models::tokenization::TokenizationUpdate, merchant_key_store: &MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl TokenizationInterface for MockDb {} #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {} #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> {}
crates/storage_impl/src/tokenization.rs
storage_impl::src::tokenization
1,887
true
// File: crates/storage_impl/src/mock_db.rs // Module: storage_impl::src::mock_db use std::sync::Arc; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models as store; use error_stack::ResultExt; use futures::lock::{Mutex, MutexGuard}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, payments::{payment_attempt::PaymentAttempt, PaymentIntent}, }; use redis_interface::RedisSettings; use crate::{errors::StorageError, redis::RedisStore}; pub mod payment_attempt; pub mod payment_intent; #[cfg(feature = "payouts")] pub mod payout_attempt; #[cfg(feature = "payouts")] pub mod payouts; pub mod redis_conn; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; #[derive(Clone)] pub struct MockDb { pub addresses: Arc<Mutex<Vec<store::Address>>>, pub configs: Arc<Mutex<Vec<store::Config>>>, pub merchant_accounts: Arc<Mutex<Vec<store::MerchantAccount>>>, pub merchant_connector_accounts: Arc<Mutex<Vec<store::MerchantConnectorAccount>>>, pub payment_attempts: Arc<Mutex<Vec<PaymentAttempt>>>, pub payment_intents: Arc<Mutex<Vec<PaymentIntent>>>, pub payment_methods: Arc<Mutex<Vec<store::PaymentMethod>>>, pub customers: Arc<Mutex<Vec<store::Customer>>>, pub refunds: Arc<Mutex<Vec<store::Refund>>>, pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>, pub redis: Arc<RedisStore>, pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>, pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>, pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>, pub events: Arc<Mutex<Vec<store::Event>>>, pub disputes: Arc<Mutex<Vec<store::Dispute>>>, pub lockers: Arc<Mutex<Vec<store::LockerMockUp>>>, pub mandates: Arc<Mutex<Vec<store::Mandate>>>, pub captures: Arc<Mutex<Vec<store::capture::Capture>>>, pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>, #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub tokenizations: Arc<Mutex<Vec<store::tokenization::Tokenization>>>, pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>, pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>, pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>, pub users: Arc<Mutex<Vec<store::user::User>>>, pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, #[cfg(feature = "payouts")] pub payout_attempt: Arc<Mutex<Vec<store::payout_attempt::PayoutAttempt>>>, #[cfg(feature = "payouts")] pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>, pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>, pub roles: Arc<Mutex<Vec<store::role::Role>>>, pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>, pub user_authentication_methods: Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>, pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>, pub hyperswitch_ai_interactions: Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>, } impl MockDb { pub async fn new(redis: &RedisSettings) -> error_stack::Result<Self, StorageError> { Ok(Self { addresses: Default::default(), configs: Default::default(), merchant_accounts: Default::default(), merchant_connector_accounts: Default::default(), payment_attempts: Default::default(), payment_intents: Default::default(), payment_methods: Default::default(), customers: Default::default(), refunds: Default::default(), processes: Default::default(), redis: Arc::new( RedisStore::new(redis) .await .change_context(StorageError::InitializationError)?, ), api_keys: Default::default(), ephemeral_keys: Default::default(), cards_info: Default::default(), events: Default::default(), disputes: Default::default(), lockers: Default::default(), mandates: Default::default(), captures: Default::default(), merchant_key_store: Default::default(), #[cfg(all(feature = "v2", feature = "tokenization_v2"))] tokenizations: Default::default(), business_profiles: Default::default(), reverse_lookups: Default::default(), payment_link: Default::default(), organizations: Default::default(), users: Default::default(), user_roles: Default::default(), authorizations: Default::default(), dashboard_metadata: Default::default(), #[cfg(feature = "payouts")] payout_attempt: Default::default(), #[cfg(feature = "payouts")] payouts: Default::default(), authentications: Default::default(), roles: Default::default(), user_key_store: Default::default(), user_authentication_methods: Default::default(), themes: Default::default(), hyperswitch_ai_interactions: Default::default(), }) } /// Returns an option of the resource if it exists pub async fn find_resource<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, ) -> CustomResult<Option<R>, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { let resource = resources.iter().find(filter_fn).cloned(); match resource { Some(res) => Ok(Some( res.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, )), None => Ok(None), } } /// Throws errors when the requested resource is not found pub async fn get_resource<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, error_message: String, ) -> CustomResult<R, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { match self .find_resource(state, key_store, resources, filter_fn) .await? { Some(res) => Ok(res), None => Err(StorageError::ValueNotFound(error_message).into()), } } pub async fn get_resources<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, resources: MutexGuard<'_, Vec<D>>, filter_fn: impl Fn(&&D) -> bool, error_message: String, ) -> CustomResult<Vec<R>, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { let resources: Vec<_> = resources.iter().filter(filter_fn).cloned().collect(); if resources.is_empty() { Err(StorageError::ValueNotFound(error_message).into()) } else { let pm_futures = resources .into_iter() .map(|pm| async { pm.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .collect::<Vec<_>>(); let domain_resources = futures::future::try_join_all(pm_futures).await?; Ok(domain_resources) } } pub async fn update_resource<D, R>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, mut resources: MutexGuard<'_, Vec<D>>, resource_updated: D, filter_fn: impl Fn(&&mut D) -> bool, error_message: String, ) -> CustomResult<R, StorageError> where D: Sync + ReverseConversion<R> + Clone, R: Conversion, { if let Some(pm) = resources.iter_mut().find(filter_fn) { *pm = resource_updated.clone(); let result = resource_updated .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(result) } else { Err(StorageError::ValueNotFound(error_message).into()) } } pub fn master_key(&self) -> &[u8] { &[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, ] } } #[cfg(not(feature = "payouts"))] impl PayoutsInterface for MockDb {} #[cfg(not(feature = "payouts"))] impl PayoutAttemptInterface for MockDb {}
crates/storage_impl/src/mock_db.rs
storage_impl::src::mock_db
2,223
true
// File: crates/storage_impl/src/callback_mapper.rs // Module: storage_impl::src::callback_mapper use diesel_models::callback_mapper::CallbackMapper as DieselCallbackMapper; use hyperswitch_domain_models::callback_mapper::CallbackMapper; use crate::DataModelExt; impl DataModelExt for CallbackMapper { type StorageModel = DieselCallbackMapper; fn to_storage_model(self) -> Self::StorageModel { DieselCallbackMapper { id: self.id, type_: self.callback_mapper_id_type, data: self.data, created_at: self.created_at, last_modified_at: self.last_modified_at, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { id: storage_model.id, callback_mapper_id_type: storage_model.type_, data: storage_model.data, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, } } }
crates/storage_impl/src/callback_mapper.rs
storage_impl::src::callback_mapper
201
true
// File: crates/storage_impl/src/lookup.rs // Module: storage_impl::src::lookup use common_utils::errors::CustomResult; use diesel_models::{ enums as storage_enums, kv, reverse_lookup::{ ReverseLookup as DieselReverseLookup, ReverseLookupNew as DieselReverseLookupNew, }, }; use error_stack::ResultExt; use redis_interface::SetnxReply; use crate::{ diesel_error_to_data_error, errors::{self, RedisErrorExt}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, try_redis_get_else_try_database_get}, DatabaseStore, RouterStore, }; #[async_trait::async_trait] pub trait ReverseLookupInterface { async fn insert_reverse_lookup( &self, _new: DieselReverseLookupNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError>; async fn get_lookup_by_lookup_id( &self, _id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError>; } #[async_trait::async_trait] impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> { async fn insert_reverse_lookup( &self, new: DieselReverseLookupNew, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let conn = self .get_master_pool() .get() .await .change_context(errors::StorageError::DatabaseConnectionError)?; new.insert(&conn).await.map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } async fn get_lookup_by_lookup_id( &self, id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let conn = utils::pg_connection_read(self).await?; DieselReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } } #[async_trait::async_trait] impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> { async fn insert_reverse_lookup( &self, new: DieselReverseLookupNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { storage_enums::MerchantStorageScheme::PostgresOnly => { self.router_store .insert_reverse_lookup(new, storage_scheme) .await } storage_enums::MerchantStorageScheme::RedisKv => { let created_rev_lookup = DieselReverseLookup { lookup_id: new.lookup_id.clone(), sk_id: new.sk_id.clone(), pk_id: new.pk_id.clone(), source: new.source.clone(), updated_by: storage_scheme.to_string(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id), }, )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() { Ok(SetnxReply::KeySet) => Ok(created_rev_lookup), Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "reverse_lookup", key: Some(created_rev_lookup.lookup_id.clone()), } .into()), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<DieselReverseLookup, errors::StorageError> { let database_call = || async { self.router_store .get_lookup_by_lookup_id(id, storage_scheme) .await }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await, storage_enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { Box::pin(kv_wrapper( self, KvOperation::<DieselReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, )) .await? .try_into_get() }; Box::pin(try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } }
crates/storage_impl/src/lookup.rs
storage_impl::src::lookup
1,204
true
// File: crates/storage_impl/src/merchant_account.rs // Module: storage_impl::src::merchant_account #[cfg(feature = "olap")] use std::collections::HashMap; use common_utils::ext_traits::AsyncExt; use diesel_models::merchant_account as storage; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, master_key::MasterKeyInterface, merchant_account::{self as domain, MerchantAccountInterface}, merchant_key_store::{MerchantKeyStore, MerchantKeyStoreInterface}, }; use masking::PeekInterface; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::{ cache, cache::{CacheKind, ACCOUNTS_CACHE}, }; #[cfg(feature = "accounts_cache")] use crate::RedisConnInterface; use crate::{ kv_router_store, store::MerchantAccountUpdateInternal, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> MerchantAccountInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .insert_merchant(state, merchant_account, merchant_key_store) .await } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .find_merchant_account_by_merchant_id(state, merchant_id, merchant_key_store) .await } #[instrument(skip_all)] async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .update_merchant(state, this, merchant_account, merchant_key_store) .await } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { self.router_store .update_specific_fields_in_merchant( state, merchant_id, merchant_account, merchant_key_store, ) .await } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { self.router_store .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { self.router_store .list_merchant_accounts_by_organization_id(state, organization_id) .await } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { self.router_store .delete_merchant_account_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { self.router_store .list_multiple_merchant_accounts(state, merchant_ids) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { self.router_store .list_merchant_and_org_ids(_state, limit, offset) .await } async fn update_all_merchant_account( &self, merchant_account: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { self.router_store .update_all_merchant_account(merchant_account) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; merchant_account .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let fetch_func = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert( state, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, merchant_id.get_string_repr(), fetch_func, &ACCOUNTS_CACHE, ) .await? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } } #[instrument(skip_all)] async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; let updated_merchant_account = Conversion::convert(this) .await .change_context(StorageError::EncryptionError)? .update(&conn, merchant_account.into()) .await .map_err(|error| report!(StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let conn = pg_accounts_connection_write(self).await?; let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields( &conn, merchant_id, merchant_account.into(), ) .await .map_err(|error| report!(StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { let fetch_by_pub_key_func = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key) .await .map_err(|error| report!(StorageError::from(error))) }; let merchant_account; #[cfg(not(feature = "accounts_cache"))] { merchant_account = fetch_by_pub_key_func().await?; } #[cfg(feature = "accounts_cache")] { merchant_account = cache::get_or_populate_in_memory( self, publishable_key, fetch_by_pub_key_func, &ACCOUNTS_CACHE, ) .await?; } let key_store = self .get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &self.master_key().peek().to_vec().into(), ) .await?; let domain_merchant_account = merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok((domain_merchant_account, key_store)) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { use futures::future::try_join_all; let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_by_organization_id(&conn, organization_id) .await .map_err(|error| report!(StorageError::from(error)))?; let db_master_key = self.master_key().peek().to_vec().into(); let merchant_key_stores = try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| { self.get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &db_master_key, ) })) .await?; let merchant_accounts = try_join_all( encrypted_merchant_accounts .into_iter() .zip(merchant_key_stores.iter()) .map(|(merchant_account, key_store)| async { merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await?; Ok(merchant_accounts) } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let conn = pg_accounts_connection_write(self).await?; let is_deleted_func = || async { storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error))) }; let is_deleted; #[cfg(not(feature = "accounts_cache"))] { is_deleted = is_deleted_func().await?; } #[cfg(feature = "accounts_cache")] { let merchant_account = storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(StorageError::from(error)))?; is_deleted = is_deleted_func().await?; publish_and_redact_merchant_account_cache(self, &merchant_account).await?; } Ok(is_deleted) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids) .await .map_err(|error| report!(StorageError::from(error)))?; let db_master_key = self.master_key().peek().to_vec().into(); let merchant_key_stores = self .list_multiple_key_stores( state, encrypted_merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id()) .cloned() .collect(), &db_master_key, ) .await?; let key_stores_by_id: HashMap<_, _> = merchant_key_stores .iter() .map(|key_store| (key_store.merchant_id.to_owned(), key_store)) .collect(); let merchant_accounts = futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map( |merchant_account| async { let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or( StorageError::ValueNotFound(format!( "merchant_key_store with merchant_id = {:?}", merchant_account.get_id() )), )?; merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }, )) .await?; Ok(merchant_accounts) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { let conn = pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset) .await .map_err(|error| report!(StorageError::from(error)))?; let merchant_and_org_ids = encrypted_merchant_accounts .into_iter() .map(|merchant_account| { let merchant_id = merchant_account.get_id().clone(); let org_id = merchant_account.organization_id; (merchant_id, org_id) }) .collect(); Ok(merchant_and_org_ids) } async fn update_all_merchant_account( &self, merchant_account: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { let conn = pg_accounts_connection_read(self).await?; let db_func = || async { storage::MerchantAccount::update_all_merchant_accounts( &conn, MerchantAccountUpdateInternal::from(merchant_account), ) .await .map_err(|error| report!(StorageError::from(error))) }; let total; #[cfg(not(feature = "accounts_cache"))] { let ma = db_func().await?; total = ma.len(); } #[cfg(feature = "accounts_cache")] { let ma = db_func().await?; publish_and_redact_all_merchant_account_cache(self, &ma).await?; total = ma.len(); } Ok(total) } } #[async_trait::async_trait] impl MerchantAccountInterface for MockDb { type Error = StorageError; #[allow(clippy::panic)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let mut accounts = self.merchant_accounts.lock().await; let account = Conversion::convert(merchant_account) .await .change_context(StorageError::EncryptionError)?; accounts.push(account.clone()); account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[allow(clippy::panic)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let accounts = self.merchant_accounts.lock().await; accounts .iter() .find(|account| account.get_id() == merchant_id) .cloned() .ok_or(StorageError::ValueNotFound(format!( "Merchant ID: {merchant_id:?} not found", )))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } async fn update_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_account_update: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let merchant_id = merchant_account.get_id().to_owned(); let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_account.get_id()) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset( Conversion::convert(merchant_account) .await .change_context(StorageError::EncryptionError)?, ); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",)) .into(), ) } async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account_update: domain::MerchantAccountUpdate, merchant_key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_id) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset(account.clone()); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await .transpose()? .ok_or( StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",)) .into(), ) } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> { let accounts = self.merchant_accounts.lock().await; let account = accounts .iter() .find(|account| { account .publishable_key .as_ref() .is_some_and(|key| key == publishable_key) }) .ok_or(StorageError::ValueNotFound(format!( "Publishable Key: {publishable_key} not found", )))?; let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await?; let merchant_account = account .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok((merchant_account, key_store)) } async fn update_all_merchant_account( &self, merchant_account_update: domain::MerchantAccountUpdate, ) -> CustomResult<usize, StorageError> { let mut accounts = self.merchant_accounts.lock().await; Ok(accounts.iter_mut().fold(0, |acc, account| { let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone()) .apply_changeset(account.clone()); *account = update; acc + 1 })) } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts.retain(|x| x.get_id() != merchant_id); Ok(true) } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| account.organization_id == *organization_id) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| merchant_ids.contains(account.get_id())) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, StorageError, > { let accounts = self.merchant_accounts.lock().await; let limit = limit.try_into().unwrap_or(accounts.len()); let offset = offset.unwrap_or(0).try_into().unwrap_or(0); let merchant_and_org_ids = accounts .iter() .skip(offset) .take(limit) .map(|account| (account.get_id().clone(), account.organization_id.clone())) .collect::<Vec<_>>(); Ok(merchant_and_org_ids) } } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_merchant_account_cache( store: &(dyn RedisConnInterface + Send + Sync), merchant_account: &storage::MerchantAccount, ) -> CustomResult<(), StorageError> { let publishable_key = merchant_account .publishable_key .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); #[cfg(feature = "v1")] let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { CacheKind::CGraph( format!( "cgraph_{}_{}", merchant_account.get_id().get_string_repr(), profile_id.get_string_repr(), ) .into(), ) }); // TODO: we will not have default profile in v2 #[cfg(feature = "v2")] let cgraph_key = None; let mut cache_keys = vec![CacheKind::Accounts( merchant_account.get_id().get_string_repr().into(), )]; cache_keys.extend(publishable_key.into_iter()); cache_keys.extend(cgraph_key.into_iter()); cache::redact_from_redis_and_publish(store, cache_keys).await?; Ok(()) } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_all_merchant_account_cache( cache: &(dyn RedisConnInterface + Send + Sync), merchant_accounts: &[storage::MerchantAccount], ) -> CustomResult<(), StorageError> { let merchant_ids = merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string()); let publishable_keys = merchant_accounts .iter() .filter_map(|m| m.publishable_key.clone()); let cache_keys: Vec<CacheKind<'_>> = merchant_ids .chain(publishable_keys) .map(|s| CacheKind::Accounts(s.into())) .collect(); cache::redact_from_redis_and_publish(cache, cache_keys).await?; Ok(()) }
crates/storage_impl/src/merchant_account.rs
storage_impl::src::merchant_account
6,137
true
// File: crates/storage_impl/src/payouts.rs // Module: storage_impl::src::payouts pub mod payout_attempt; #[allow(clippy::module_inception)] pub mod payouts; use diesel_models::{payout_attempt::PayoutAttempt, payouts::Payouts}; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Payouts {} impl KvStorePartition for PayoutAttempt {}
crates/storage_impl/src/payouts.rs
storage_impl::src::payouts
91
true
// File: crates/storage_impl/src/database.rs // Module: storage_impl::src::database pub mod store;
crates/storage_impl/src/database.rs
storage_impl::src::database
24
true
// File: crates/storage_impl/src/cards_info.rs // Module: storage_impl::src::cards_info pub use diesel_models::{CardInfo, UpdateCardInfo}; use error_stack::report; use hyperswitch_domain_models::cards_info::CardsInfoInterface; use router_env::{instrument, tracing}; use crate::{ errors::StorageError, kv_router_store::KVRouterStore, redis::kv_store::KvStorePartition, utils::{pg_connection_read, pg_connection_write}, CustomResult, DatabaseStore, MockDb, RouterStore, }; impl KvStorePartition for CardInfo {} #[async_trait::async_trait] impl<T: DatabaseStore> CardsInfoInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { let conn = pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(StorageError::from(error))) } } #[async_trait::async_trait] impl<T: DatabaseStore> CardsInfoInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { let conn = pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { let conn = pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(StorageError::from(error))) } } #[async_trait::async_trait] impl CardsInfoInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> { Ok(self .cards_info .lock() .await .iter() .find(|ci| ci.card_iin == card_iin) .cloned()) } async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, StorageError> { Err(StorageError::MockDbError)? } async fn update_card_info( &self, _card_iin: String, _data: UpdateCardInfo, ) -> CustomResult<CardInfo, StorageError> { Err(StorageError::MockDbError)? } }
crates/storage_impl/src/cards_info.rs
storage_impl::src::cards_info
845
true
// File: crates/storage_impl/src/payment_method.rs // Module: storage_impl::src::payment_method pub use diesel_models::payment_method::PaymentMethod; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for PaymentMethod {} use common_enums::enums::MerchantStorageScheme; use common_utils::{errors::CustomResult, id_type, types::keymanager::KeyManagerState}; #[cfg(feature = "v1")] use diesel_models::kv; use diesel_models::payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::behaviour::ReverseConversion; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface}, }; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ diesel_error_to_data_error, errors, kv_router_store::{FindResourceBy, KVRouterStore}, utils::{pg_connection_read, pg_connection_write}, DatabaseStore, RouterStore, }; #[cfg(feature = "v1")] use crate::{ kv_router_store::{FilterResourceParams, InsertResourceParams, UpdateResourceParams}, redis::kv_store::{Op, PartitionKey}, }; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> { type Error = errors::StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), FindResourceBy::LookupId(format!("payment_method_{payment_method_id}")), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_id(&conn, payment_method_id), FindResourceBy::LookupId(format!( "payment_method_{}", payment_method_id.get_string_repr() )), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( state, key_store, storage_scheme, PaymentMethod::find_by_locker_id(&conn, locker_id), FindResourceBy::LookupId(format!("payment_method_locker_{locker_id}")), ) .await } // not supported in kv #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_customer_id_merchant_id_status( customer_id, merchant_id, status, ) .await } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_payment_method_count_by_merchant_id_status(merchant_id, status) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .insert_payment_method(state, key_store, payment_method, storage_scheme) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; let mut payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; payment_method_new.update_storage_scheme(storage_scheme); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &payment_method_new.merchant_id.clone(), customer_id: &payment_method_new.customer_id.clone(), }; let identifier = format!("payment_method_id_{}", payment_method_new.get_id()); let lookup_id1 = format!("payment_method_{}", payment_method_new.get_id()); let mut reverse_lookups = vec![lookup_id1]; if let Some(locker_id) = &payment_method_new.locker_id { reverse_lookups.push(format!("payment_method_locker_{locker_id}")) } let payment_method = (&payment_method_new.clone()).into(); self.insert_resource( state, key_store, storage_scheme, payment_method_new.clone().insert(&conn), payment_method, InsertResourceParams { insertable: kv::Insertable::PaymentMethod(payment_method_new.clone()), reverse_lookups, key, identifier, resource_type: "payment_method", }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let merchant_id = payment_method.merchant_id.clone(); let customer_id = payment_method.customer_id.clone(); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let conn = pg_connection_write(self).await?; let field = format!("payment_method_id_{}", payment_method.get_id().clone()); let p_update: PaymentMethodUpdateInternal = payment_method_update.convert_to_payment_method_update(storage_scheme); let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone()); self.update_resource( state, key_store, storage_scheme, payment_method .clone() .update_with_payment_method_id(&conn, p_update.clone()), updated_payment_method, UpdateResourceParams { updateable: kv::Updateable::PaymentMethodUpdate(Box::new( kv::PaymentMethodUpdateMems { orig: payment_method.clone(), update_data: p_update.clone(), }, )), operation: Op::Update( key.clone(), &field, payment_method.clone().updated_by.as_deref(), ), }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .update_payment_method( state, key_store, payment_method, payment_method_update, storage_scheme, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_customer_id_merchant_id_list( state, key_store, customer_id, merchant_id, limit, ) .await } #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_list_by_global_customer_id(state, key_store, customer_id, limit) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.filter_resources( state, key_store, storage_scheme, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), |pm| pm.status == status, FilterResourceParams { key: PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, pattern: "payment_method_id_*", limit, }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { self.router_store .find_payment_method_by_global_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method_by_merchant_id_payment_method_id( state, key_store, merchant_id, payment_method_id, ) .await } // Soft delete, Check if KV stuff is needed here #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .delete_payment_method(state, key_store, payment_method) .await } // Check if KV stuff is needed here #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { self.router_store .find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_payment_method_id(&conn, payment_method_id), ) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_id(&conn, payment_method_id), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_locker_id(&conn, locker_id), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, ) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let conn = pg_connection_read(self).await?; PaymentMethod::get_count_by_merchant_id_status(&conn, merchant_id, status) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[instrument(skip_all)] async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_new = payment_method .construct_new() .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database(state, key_store, payment_method_new.insert(&conn)) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( state, key_store, payment_method.update_with_payment_method_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; self.call_database( state, key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit), ) .await } // Need to fix this once we move to payment method for customer #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_global_customer_id(&conn, id, limit), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resources( state, key_store, PaymentMethod::find_by_global_customer_id_merchant_id_status( &conn, customer_id, merchant_id, status, limit, ), ) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_write(self).await?; self.call_database( state, key_store, PaymentMethod::delete_by_merchant_id_payment_method_id( &conn, merchant_id, payment_method_id, ), ) .await } #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await .change_context(errors::StorageError::DecryptionError)?; let conn = pg_connection_write(self).await?; let payment_method_update = PaymentMethodUpdate::StatusUpdate { status: Some(common_enums::PaymentMethodStatus::Inactive), }; self.call_database( state, key_store, payment_method.update_with_id(&conn, payment_method_update.into()), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let conn = pg_connection_read(self).await?; self.call_database( state, key_store, PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id), ) .await } } #[async_trait::async_trait] impl PaymentMethodInterface for MockDb { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.get_id() == payment_method_id, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v1")] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.locker_id == Some(locker_id.to_string()), "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v1")] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let count = payment_methods .iter() .filter(|pm| pm.merchant_id == *merchant_id && pm.status == status) .count(); i64::try_from(count).change_context(errors::StorageError::MockDbError) } async fn insert_payment_method( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; let pm = Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::DecryptionError)?; payment_methods.push(pm); Ok(payment_method) } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resources( state, key_store, payment_methods, |pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id, "cannot find payment method".to_string(), ) .await } // Need to fix this once we complete v2 payment method #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _id: &id_type::GlobalCustomerId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { todo!() } #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resources( state, key_store, payment_methods, |pm| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }, "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, _limit: Option<i64>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; let find_pm_by = |pm: &&PaymentMethod| { pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status }; let error_message = "cannot find payment method".to_string(); self.get_resources(state, key_store, payment_methods, find_pm_by, error_message) .await } #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let mut payment_methods = self.payment_methods.lock().await; match payment_methods .iter() .position(|pm| pm.merchant_id == *merchant_id && pm.get_id() == payment_method_id) { Some(index) => { let deleted_payment_method = payment_methods.remove(index); Ok(deleted_payment_method .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?) } None => Err(errors::StorageError::ValueNotFound( "cannot find payment method to delete".to_string(), ) .into()), } } async fn update_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update) .apply_changeset( Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::EncryptionError)?, ); self.update_resource::<PaymentMethod, _>( state, key_store, self.payment_methods.lock().await, payment_method_updated, |pm| pm.get_id() == payment_method.get_id(), "cannot update payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method_update = PaymentMethodUpdate::StatusUpdate { status: Some(common_enums::PaymentMethodStatus::Inactive), }; let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update) .apply_changeset( Conversion::convert(payment_method.clone()) .await .change_context(errors::StorageError::EncryptionError)?, ); self.update_resource::<PaymentMethod, _>( state, key_store, self.payment_methods.lock().await, payment_method_updated, |pm| pm.get_id() == payment_method.get_id(), "cannot find payment method".to_string(), ) .await } #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_methods = self.payment_methods.lock().await; self.get_resource::<PaymentMethod, _>( state, key_store, payment_methods, |pm| pm.locker_fingerprint_id == Some(fingerprint_id.to_string()), "cannot find payment method".to_string(), ) .await } }
crates/storage_impl/src/payment_method.rs
storage_impl::src::payment_method
7,319
true
// File: crates/storage_impl/src/merchant_connector_account.rs // Module: storage_impl::src::merchant_connector_account use async_bb8_diesel::AsyncConnection; use common_utils::{encryption::Encryption, ext_traits::AsyncExt}; use diesel_models::merchant_connector_account as storage; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_connector_account::{self as domain, MerchantConnectorAccountInterface}, merchant_key_store::MerchantKeyStore, }; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::cache; use crate::{ kv_router_store, utils::{pg_accounts_connection_read, pg_accounts_connection_write}, CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError, }; #[async_trait::async_trait] impl<T: DatabaseStore> MerchantConnectorAccountInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_connector_label( state, merchant_id, connector_label, key_store, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_profile_id_connector_name( state, profile_id, connector_name, key_store, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_connector_name( state, merchant_id, connector_name, key_store, ) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( state, merchant_id, merchant_connector_id, key_store, ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .find_merchant_connector_account_by_id(state, id, key_store) .await } #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .insert_merchant_connector_account(state, t, key_store) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .list_enabled_connector_accounts_by_profile_id( state, profile_id, key_store, connector_type, ) .await } #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> { self.router_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( state, merchant_id, get_disabled, key_store, ) .await } #[instrument(skip_all)] #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { self.router_store .list_connector_account_by_profile_id(state, profile_id, key_store) .await } #[instrument(skip_all)] async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error> { self.router_store .update_multiple_merchant_connector_accounts(merchant_connector_accounts) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.router_store .update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { self.update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( merchant_id, merchant_connector_id, ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_connector_account_by_id(id) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector( &conn, merchant_id, connector_label, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(Self::Error::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", merchant_id.get_string_repr(), connector_label), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_profile_id_connector_name( &conn, profile_id, connector_name, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", profile_id.get_string_repr(), connector_name), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector_name( &conn, merchant_id, connector_name, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!( "{}_{}", merchant_id.get_string_repr(), merchant_connector_id.get_string_repr() ), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let find_call = || async { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_id(&conn, id) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone(), ) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, id.get_string_repr(), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let conn = pg_accounts_connection_write(self).await?; t.construct_new() .await .change_context(Self::Error::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await } async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_enabled_by_profile_id( &conn, profile_id, connector_type, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> { let conn = pg_accounts_connection_read(self).await?; let merchant_connector_account_vec = storage::MerchantConnectorAccount::find_by_merchant_id( &conn, merchant_id, get_disabled, ) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await?; Ok(domain::MerchantConnectorAccounts::new( merchant_connector_account_vec, )) } #[instrument(skip_all)] #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error> { let conn = pg_accounts_connection_write(self).await?; async fn update_call( connection: &diesel_models::PgPooledConn, (merchant_connector_account, mca_update): ( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, ), ) -> Result<(), error_stack::Report<StorageError>> { Conversion::convert(merchant_connector_account) .await .change_context(StorageError::EncryptionError)? .update(connection, mca_update) .await .map_err(|error| report!(StorageError::from(error)))?; Ok(()) } conn.transaction_async(|connection_pool| async move { for (merchant_connector_account, update_merchant_connector_account) in merchant_connector_accounts { #[cfg(feature = "v1")] let _connector_name = merchant_connector_account.connector_name.clone(); #[cfg(feature = "v2")] let _connector_name = merchant_connector_account.connector_name.to_string(); let _profile_id = merchant_connector_account.profile_id.clone(); let _merchant_id = merchant_connector_account.merchant_id.clone(); let _merchant_connector_id = merchant_connector_account.get_id().clone(); let update = update_call( &connection_pool, ( merchant_connector_account, update_merchant_connector_account, ), ); #[cfg(feature = "accounts_cache")] // Redact all caches as any of might be used because of backwards compatibility Box::pin(cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], || update, )) .await .map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); Self::Error::DatabaseConnectionError })?; #[cfg(not(feature = "accounts_cache"))] { update.await.map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); Self::Error::DatabaseConnectionError })?; } } Ok::<_, Self::Error>(()) }) .await?; Ok(()) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let _connector_name = this.connector_name.clone(); let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.merchant_connector_id.clone(); let update_call = || async { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(Self::Error::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(Self::Error::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr(), ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> { let _connector_name = this.connector_name; let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.get_id().clone(); let update_call = || async { let conn = pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(Self::Error::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(Self::Error::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(Self::Error::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( _merchant_connector_id.get_string_repr().to_string().into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { let conn = pg_accounts_connection_write(self).await?; let delete_call = || async { storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(feature = "accounts_cache")] { // We need to fetch mca here because the key that's saved in cache in // {merchant_id}_{connector_label}. // Used function from storage model to reuse the connection that made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(Self::Error::from(error)))?; let _profile_id = mca .profile_id .ok_or(Self::Error::ValueNotFound("profile_id".to_string()))?; cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!( "{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], delete_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { delete_call().await } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error> { let conn = pg_accounts_connection_write(self).await?; let delete_call = || async { storage::MerchantConnectorAccount::delete_by_id(&conn, id) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(feature = "accounts_cache")] { // We need to fetch mca here because the key that's saved in cache in // {merchant_id}_{connector_label}. // Used function from storage model to reuse the connection that made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find_by_id(&conn, id) .await .map_err(|error| report!(Self::Error::from(error)))?; let _profile_id = mca.profile_id; cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!( "{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], delete_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { delete_call().await } } } #[async_trait::async_trait] impl MerchantConnectorAccountInterface for MockDb { type Error = StorageError; async fn update_multiple_merchant_connector_accounts( &self, _merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), StorageError> { // No need to implement this function for `MockDb` as this function will be removed after the // apple pay certificate migration Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.merchant_id == *merchant_id && account.connector_label == Some(connector.to_string()) }) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } async fn list_enabled_connector_accounts_by_profile_id( &self, _state: &KeyManagerState, _profile_id: &common_utils::id_type::ProfileId, _key_store: &MerchantKeyStore, _connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account| { account.merchant_id == *merchant_id && account.connector_name == connector_name }) .cloned() .collect::<Vec<_>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, ) } Ok(output) } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let maybe_mca = self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.profile_id.eq(&Some(profile_id.to_owned())) && account.connector_name == connector_name }) .cloned(); match maybe_mca { Some(mca) => mca .to_owned() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError), None => Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()), } } #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.merchant_id == *merchant_id && account.merchant_connector_id == *merchant_connector_id }) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| account.get_id() == *id) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } #[cfg(feature = "v1")] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { merchant_id: t.merchant_id, connector_name: t.connector_name, connector_account_details: t.connector_account_details.into(), test_mode: t.test_mode, disabled: t.disabled, merchant_connector_id: t.merchant_connector_id.clone(), id: Some(t.merchant_connector_id), payment_methods_enabled: t.payment_methods_enabled, metadata: t.metadata, frm_configs: None, frm_config: t.frm_configs, connector_type: t.connector_type, connector_label: t.connector_label, business_country: t.business_country, business_label: t.business_label, business_sub_label: t.business_sub_label, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), connector_webhook_details: t.connector_webhook_details, profile_id: Some(t.profile_id), applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, connector_wallets_details: t.connector_wallets_details.map(Encryption::from), additional_merchant_data: t.additional_merchant_data.map(|data| data.into()), version: t.version, }; accounts.push(account.clone()); account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { id: t.id, merchant_id: t.merchant_id, connector_name: t.connector_name, connector_account_details: t.connector_account_details.into(), disabled: t.disabled, payment_methods_enabled: t.payment_methods_enabled, metadata: t.metadata, frm_config: t.frm_configs, connector_type: t.connector_type, connector_label: t.connector_label, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), connector_webhook_details: t.connector_webhook_details, profile_id: t.profile_id, applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, connector_wallets_details: t.connector_wallets_details.map(Encryption::from), additional_merchant_data: t.additional_merchant_data.map(|data| data.into()), version: t.version, feature_metadata: t.feature_metadata.map(From::from), }; accounts.push(account.clone()); account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(StorageError::DecryptionError) } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account: &&storage::MerchantConnectorAccount| { if get_disabled { account.merchant_id == *merchant_id } else { account.merchant_id == *merchant_id && account.disabled == Some(false) } }) .cloned() .collect::<Vec<storage::MerchantConnectorAccount>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, ) } Ok(domain::MerchantConnectorAccounts::new(output)) } #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account: &&storage::MerchantConnectorAccount| { account.profile_id == *profile_id }) .cloned() .collect::<Vec<storage::MerchantConnectorAccount>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, ) } Ok(output) } #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mca_update_res = self .merchant_connector_accounts .lock() .await .iter_mut() .find(|account| account.merchant_connector_id == this.merchant_connector_id) .map(|a| { let updated = merchant_connector_account.create_merchant_connector_account(a.clone()); *a = updated.clone(); updated }) .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await; match mca_update_res { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to update".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, StorageError> { let mca_update_res = self .merchant_connector_accounts .lock() .await .iter_mut() .find(|account| account.get_id() == this.get_id()) .map(|a| { let updated = merchant_connector_account.create_merchant_connector_account(a.clone()); *a = updated.clone(); updated }) .async_map(|account| async { account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(StorageError::DecryptionError) }) .await; match mca_update_res { Some(result) => result, None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to update".to_string(), ) .into()) } } } #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; match accounts.iter().position(|account| { account.merchant_id == *merchant_id && account.merchant_connector_id == *merchant_connector_id }) { Some(index) => { accounts.remove(index); return Ok(true); } None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to delete".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; match accounts.iter().position(|account| account.get_id() == *id) { Some(index) => { accounts.remove(index); return Ok(true); } None => { return Err(StorageError::ValueNotFound( "cannot find merchant connector account to delete".to_string(), ) .into()) } } } }
crates/storage_impl/src/merchant_connector_account.rs
storage_impl::src::merchant_connector_account
10,501
true
// File: crates/storage_impl/src/config.rs // Module: storage_impl::src::config use common_utils::DbConnectionParams; use hyperswitch_domain_models::master_key::MasterKeyInterface; use masking::{PeekInterface, Secret}; use crate::{kv_router_store, DatabaseStore, MockDb, RouterStore}; #[derive(Debug, Clone, serde::Deserialize)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, pub queue_strategy: QueueStrategy, pub min_idle: Option<u32>, pub max_lifetime: Option<u64>, } impl DbConnectionParams for Database { fn get_username(&self) -> &str { &self.username } fn get_password(&self) -> Secret<String> { self.password.clone() } fn get_host(&self) -> &str { &self.host } fn get_port(&self) -> u16 { self.port } fn get_dbname(&self) -> &str { &self.dbname } } #[derive(Debug, serde::Deserialize, Clone, Copy, Default)] #[serde(rename_all = "PascalCase")] pub enum QueueStrategy { #[default] Fifo, Lifo, } impl From<QueueStrategy> for bb8::QueueStrategy { fn from(value: QueueStrategy) -> Self { match value { QueueStrategy::Fifo => Self::Fifo, QueueStrategy::Lifo => Self::Lifo, } } } impl Default for Database { fn default() -> Self { Self { username: String::new(), password: Secret::<String>::default(), host: "localhost".into(), port: 5432, dbname: String::new(), pool_size: 5, connection_timeout: 10, queue_strategy: QueueStrategy::default(), min_idle: None, max_lifetime: None, } } } impl<T: DatabaseStore> MasterKeyInterface for kv_router_store::KVRouterStore<T> { fn get_master_key(&self) -> &[u8] { self.master_key().peek() } } impl<T: DatabaseStore> MasterKeyInterface for RouterStore<T> { fn get_master_key(&self) -> &[u8] { self.master_key().peek() } } /// Default dummy key for MockDb impl MasterKeyInterface for MockDb { fn get_master_key(&self) -> &[u8] { self.master_key() } }
crates/storage_impl/src/config.rs
storage_impl::src::config
577
true
// File: crates/storage_impl/src/configs.rs // Module: storage_impl::src::configs use diesel_models::configs as storage; use error_stack::report; use hyperswitch_domain_models::configs::ConfigInterface; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store, redis::{ cache, cache::{CacheKind, CONFIG_CACHE}, }, store::ConfigUpdateInternal, CustomResult, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> ConfigInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, Self::Error> { self.router_store.insert_config(config).await } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { self.router_store .update_config_in_database(key, config_update) .await } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { self.router_store .update_config_by_key(key, config_update) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, StorageError> { self.router_store.find_config_by_key_from_db(key).await } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { self.router_store.find_config_by_key(key).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, StorageError> { self.router_store .find_config_by_key_unwrap_or(key, default_config) .await } #[instrument(skip_all)] async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { self.router_store.delete_config_by_key(key).await } } #[async_trait::async_trait] impl<T: DatabaseStore> ConfigInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; let inserted = config .insert(&conn) .await .map_err(|error| report!(StorageError::from(error)))?; cache::redact_from_redis_and_publish(self, [CacheKind::Config((&inserted.key).into())]) .await?; Ok(inserted) } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::update_by_key(&conn, key, config_update) .await .map_err(|error| report!(StorageError::from(error))) } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, StorageError> { cache::publish_and_redact(self, CacheKind::Config(key.into()), || { self.update_config_in_database(key, config_update) }) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { let find_config_by_key_from_db = || async { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) }; cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, StorageError> { let find_else_unwrap_or = || async { let conn = connection::pg_connection_write(self).await?; match storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error))) { Ok(a) => Ok(a), Err(err) => { if err.current_context().is_db_not_found() { default_config .map(|c| { storage::ConfigNew { key: key.to_string(), config: c, } .into() }) .ok_or(err) } else { Err(err) } } } }; cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> { let conn = connection::pg_connection_write(self).await?; let deleted = storage::Config::delete_by_key(&conn, key) .await .map_err(|error| report!(StorageError::from(error)))?; cache::redact_from_redis_and_publish(self, [CacheKind::Config((&deleted.key).into())]) .await?; Ok(deleted) } } #[async_trait::async_trait] impl ConfigInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, Self::Error> { let mut configs = self.configs.lock().await; let config_new = storage::Config { key: config.key, config: config.config, }; configs.push(config_new.clone()); Ok(config_new) } async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error> { self.update_config_by_key(key, config_update).await } async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, Self::Error> { let result = self .configs .lock() .await .iter_mut() .find(|c| c.key == key) .ok_or_else(|| { StorageError::ValueNotFound("cannot find config to update".to_string()).into() }) .map(|c| { let config_updated = ConfigUpdateInternal::from(config_update).create_config(c.clone()); *c = config_updated.clone(); config_updated }); result } async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> { let mut configs = self.configs.lock().await; let result = configs .iter() .position(|c| c.key == key) .map(|index| configs.remove(index)) .ok_or_else(|| { StorageError::ValueNotFound("cannot find config to delete".to_string()).into() }); result } async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> { let configs = self.configs.lock().await; let config = configs.iter().find(|c| c.key == key).cloned(); config.ok_or_else(|| StorageError::ValueNotFound("cannot find config".to_string()).into()) } async fn find_config_by_key_unwrap_or( &self, key: &str, _default_config: Option<String>, ) -> CustomResult<storage::Config, Self::Error> { self.find_config_by_key(key).await } async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, Self::Error> { self.find_config_by_key(key).await } }
crates/storage_impl/src/configs.rs
storage_impl::src::configs
2,129
true
// File: crates/storage_impl/src/payments.rs // Module: storage_impl::src::payments pub mod payment_attempt; pub mod payment_intent; use diesel_models::{payment_attempt::PaymentAttempt, PaymentIntent}; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for PaymentIntent {} impl KvStorePartition for PaymentAttempt {}
crates/storage_impl/src/payments.rs
storage_impl::src::payments
73
true
// File: crates/storage_impl/src/lib.rs // Module: storage_impl::src::lib use std::{fmt::Debug, sync::Arc}; use common_utils::types::TenantConfig; use diesel_models as store; use error_stack::ResultExt; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; use masking::StrongSecret; use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore}; mod address; pub mod business_profile; pub mod callback_mapper; pub mod cards_info; pub mod config; pub mod configs; pub mod connection; pub mod customers; pub mod database; pub mod errors; pub mod invoice; pub mod kv_router_store; pub mod lookup; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod metrics; pub mod mock_db; pub mod payment_method; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod redis; pub mod refund; mod reverse_lookup; pub mod subscription; pub mod utils; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use database::store::PgPool; pub mod tokenization; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; pub use mock_db::MockDb; use redis_interface::{errors::RedisError, RedisConnectionPool, SaddReply}; #[cfg(not(feature = "payouts"))] pub use crate::database::store::Store; pub use crate::{database::store::DatabaseStore, errors::StorageError}; #[derive(Debug, Clone)] pub struct RouterStore<T: DatabaseStore> { db_store: T, cache_store: Arc<RedisStore>, master_encryption_key: StrongSecret<Vec<u8>>, pub request_id: Option<String>, } #[async_trait::async_trait] impl<T: DatabaseStore> DatabaseStore for RouterStore<T> where T::Config: Send, { type Config = ( T::Config, redis_interface::RedisSettings, StrongSecret<Vec<u8>>, tokio::sync::oneshot::Sender<()>, &'static str, ); async fn new( config: Self::Config, tenant_config: &dyn TenantConfig, test_transaction: bool, ) -> error_stack::Result<Self, StorageError> { let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) = config; if test_transaction { Self::test_store(db_conf, tenant_config, &cache_conf, encryption_key) .await .attach_printable("failed to create test router store") } else { Self::from_config( db_conf, tenant_config, encryption_key, Self::cache_store(&cache_conf, cache_error_signal).await?, inmemory_cache_stream, ) .await .attach_printable("failed to create store") } } fn get_master_pool(&self) -> &PgPool { self.db_store.get_master_pool() } fn get_replica_pool(&self) -> &PgPool { self.db_store.get_replica_pool() } fn get_accounts_master_pool(&self) -> &PgPool { self.db_store.get_accounts_master_pool() } fn get_accounts_replica_pool(&self) -> &PgPool { self.db_store.get_accounts_replica_pool() } } impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> { fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> { self.cache_store.get_redis_conn() } } impl<T: DatabaseStore> RouterStore<T> { pub async fn from_config( db_conf: T::Config, tenant_config: &dyn TenantConfig, encryption_key: StrongSecret<Vec<u8>>, cache_store: Arc<RedisStore>, inmemory_cache_stream: &str, ) -> error_stack::Result<Self, StorageError> { let db_store = T::new(db_conf, tenant_config, false).await?; let redis_conn = cache_store.redis_conn.clone(); let cache_store = Arc::new(RedisStore { redis_conn: Arc::new(RedisConnectionPool::clone( &redis_conn, tenant_config.get_redis_key_prefix(), )), }); cache_store .redis_conn .subscribe(inmemory_cache_stream) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to subscribe to inmemory cache stream")?; Ok(Self { db_store, cache_store, master_encryption_key: encryption_key, request_id: None, }) } pub async fn cache_store( cache_conf: &redis_interface::RedisSettings, cache_error_signal: tokio::sync::oneshot::Sender<()>, ) -> error_stack::Result<Arc<RedisStore>, StorageError> { let cache_store = RedisStore::new(cache_conf) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to create cache store")?; cache_store.set_error_callback(cache_error_signal); Ok(Arc::new(cache_store)) } pub fn master_key(&self) -> &StrongSecret<Vec<u8>> { &self.master_encryption_key } pub async fn call_database<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, execute_query: R, ) -> error_stack::Result<D, StorageError> where D: Debug + Sync + Conversion, R: futures::Future<Output = error_stack::Result<M, diesel_models::errors::DatabaseError>> + Send, M: ReverseConversion<D>, { execute_query .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } pub async fn find_optional_resource<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, execute_query_fut: R, ) -> error_stack::Result<Option<D>, StorageError> where D: Debug + Sync + Conversion, R: futures::Future< Output = error_stack::Result<Option<M>, diesel_models::errors::DatabaseError>, > + Send, M: ReverseConversion<D>, { match execute_query_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? { Some(resource) => Ok(Some( resource .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?, )), None => Ok(None), } } pub async fn find_resources<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, execute_query: R, ) -> error_stack::Result<Vec<D>, StorageError> where D: Debug + Sync + Conversion, R: futures::Future< Output = error_stack::Result<Vec<M>, diesel_models::errors::DatabaseError>, > + Send, M: ReverseConversion<D>, { let resource_futures = execute_query .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })? .into_iter() .map(|resource| async { resource .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .collect::<Vec<_>>(); let resources = futures::future::try_join_all(resource_futures).await?; Ok(resources) } /// # Panics /// /// Will panic if `CONNECTOR_AUTH_FILE_PATH` is not set pub async fn test_store( db_conf: T::Config, tenant_config: &dyn TenantConfig, cache_conf: &redis_interface::RedisSettings, encryption_key: StrongSecret<Vec<u8>>, ) -> error_stack::Result<Self, StorageError> { // TODO: create an error enum and return proper error here let db_store = T::new(db_conf, tenant_config, true).await?; let cache_store = RedisStore::new(cache_conf) .await .change_context(StorageError::InitializationError) .attach_printable("failed to create redis cache")?; Ok(Self { db_store, cache_store: Arc::new(cache_store), master_encryption_key: encryption_key, request_id: None, }) } } // TODO: This should not be used beyond this crate // Remove the pub modified once StorageScheme usage is completed pub trait DataModelExt { type StorageModel; fn to_storage_model(self) -> Self::StorageModel; fn from_storage_model(storage_model: Self::StorageModel) -> Self; } pub(crate) fn diesel_error_to_data_error( diesel_error: diesel_models::errors::DatabaseError, ) -> StorageError { match diesel_error { diesel_models::errors::DatabaseError::DatabaseConnectionError => { StorageError::DatabaseConnectionError } diesel_models::errors::DatabaseError::NotFound => { StorageError::ValueNotFound("Value not found".to_string()) } diesel_models::errors::DatabaseError::UniqueViolation => StorageError::DuplicateValue { entity: "entity ", key: None, }, _ => StorageError::DatabaseError(error_stack::report!(diesel_error)), } } #[async_trait::async_trait] pub trait UniqueConstraints { fn unique_constraints(&self) -> Vec<String>; fn table_name(&self) -> &str; async fn check_for_constraints( &self, redis_conn: &Arc<RedisConnectionPool>, ) -> CustomResult<(), RedisError> { let constraints = self.unique_constraints(); let sadd_result = redis_conn .sadd( &format!("unique_constraint:{}", self.table_name()).into(), constraints, ) .await?; match sadd_result { SaddReply::KeyNotSet => Err(error_stack::report!(RedisError::SetAddMembersFailed)), SaddReply::KeySet => Ok(()), } } } impl UniqueConstraints for diesel_models::Address { fn unique_constraints(&self) -> Vec<String> { vec![format!("address_{}", self.address_id)] } fn table_name(&self) -> &str { "Address" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentIntent { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "PaymentIntent" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentIntent { #[cfg(feature = "v1")] fn unique_constraints(&self) -> Vec<String> { vec![format!( "pi_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr() )] } #[cfg(feature = "v2")] fn unique_constraints(&self) -> Vec<String> { vec![format!("pi_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "PaymentIntent" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!( "pa_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id )] } fn table_name(&self) -> &str { "PaymentAttempt" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!("pa_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "PaymentAttempt" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![format!( "refund_{}_{}", self.merchant_id.get_string_repr(), self.refund_id )] } fn table_name(&self) -> &str { "Refund" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "Refund" } } impl UniqueConstraints for diesel_models::ReverseLookup { fn unique_constraints(&self) -> Vec<String> { vec![format!("reverselookup_{}", self.lookup_id)] } fn table_name(&self) -> &str { "ReverseLookup" } } #[cfg(feature = "payouts")] impl UniqueConstraints for diesel_models::Payouts { fn unique_constraints(&self) -> Vec<String> { vec![format!( "po_{}_{}", self.merchant_id.get_string_repr(), self.payout_id.get_string_repr() )] } fn table_name(&self) -> &str { "Payouts" } } #[cfg(feature = "payouts")] impl UniqueConstraints for diesel_models::PayoutAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!( "poa_{}_{}", self.merchant_id.get_string_repr(), self.payout_attempt_id )] } fn table_name(&self) -> &str { "PayoutAttempt" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentMethod { fn unique_constraints(&self) -> Vec<String> { vec![format!("paymentmethod_{}", self.payment_method_id)] } fn table_name(&self) -> &str { "PaymentMethod" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentMethod { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] } fn table_name(&self) -> &str { "PaymentMethod" } } impl UniqueConstraints for diesel_models::Mandate { fn unique_constraints(&self) -> Vec<String> { vec![format!( "mand_{}_{}", self.merchant_id.get_string_repr(), self.mandate_id )] } fn table_name(&self) -> &str { "Mandate" } } #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::Customer { fn unique_constraints(&self) -> Vec<String> { vec![format!( "customer_{}_{}", self.customer_id.get_string_repr(), self.merchant_id.get_string_repr(), )] } fn table_name(&self) -> &str { "Customer" } } #[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::Customer { fn unique_constraints(&self) -> Vec<String> { vec![format!("customer_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "Customer" } } #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutAttemptInterface for RouterStore<T> {} #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutsInterface for RouterStore<T> {} #[cfg(all(feature = "v2", feature = "tokenization_v2"))] impl UniqueConstraints for diesel_models::tokenization::Tokenization { fn unique_constraints(&self) -> Vec<String> { vec![format!("id_{}", self.id.get_string_repr())] } fn table_name(&self) -> &str { "tokenization" } }
crates/storage_impl/src/lib.rs
storage_impl::src::lib
3,594
true
// File: crates/storage_impl/src/subscription.rs // Module: storage_impl::src::subscription use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; pub use diesel_models::subscription::Subscription; use error_stack::ResultExt; pub use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, subscription::{ Subscription as DomainSubscription, SubscriptionInterface, SubscriptionUpdate as DomainSubscriptionUpdate, }, }; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { let sub_new = subscription_new .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database(state, key_store, sub_new.insert(&conn)) .await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { let conn = connection::pg_connection_write(self).await?; self.call_database( state, key_store, Subscription::find_by_merchant_id_subscription_id(&conn, merchant_id, subscription_id), ) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { let sub_new = data .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database( state, key_store, Subscription::update_subscription_entry(&conn, merchant_id, subscription_id, sub_new), ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> SubscriptionInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .insert_subscription_entry(state, key_store, subscription_new) .await } #[instrument(skip_all)] async fn find_by_merchant_id_subscription_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .find_by_merchant_id_subscription_id(state, key_store, merchant_id, subscription_id) .await } #[instrument(skip_all)] async fn update_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { self.router_store .update_subscription_entry(state, key_store, merchant_id, subscription_id, data) .await } } #[async_trait::async_trait] impl SubscriptionInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_subscription_entry( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _subscription_new: DomainSubscription, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } async fn find_by_merchant_id_subscription_id( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } async fn update_subscription_entry( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _merchant_id: &common_utils::id_type::MerchantId, _subscription_id: String, _data: DomainSubscriptionUpdate, ) -> CustomResult<DomainSubscription, StorageError> { Err(StorageError::MockDbError)? } }
crates/storage_impl/src/subscription.rs
storage_impl::src::subscription
1,129
true
// File: crates/storage_impl/src/address.rs // Module: storage_impl::src::address use diesel_models::address::Address; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Address {}
crates/storage_impl/src/address.rs
storage_impl::src::address
48
true
// File: crates/storage_impl/src/metrics.rs // Module: storage_impl::src::metrics use router_env::{counter_metric, gauge_metric, global_meter}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // Metrics for KV counter_metric!(KV_OPERATION_SUCCESSFUL, GLOBAL_METER); counter_metric!(KV_OPERATION_FAILED, GLOBAL_METER); counter_metric!(KV_PUSHED_TO_DRAINER, GLOBAL_METER); counter_metric!(KV_FAILED_TO_PUSH_TO_DRAINER, GLOBAL_METER); counter_metric!(KV_SOFT_KILL_ACTIVE_UPDATE, GLOBAL_METER); // Metrics for In-memory cache gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_HIT, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_MISS, GLOBAL_METER); counter_metric!(IN_MEMORY_CACHE_EVICTION_COUNT, GLOBAL_METER);
crates/storage_impl/src/metrics.rs
storage_impl::src::metrics
196
true
// File: crates/storage_impl/src/refund.rs // Module: storage_impl::src::refund use diesel_models::refund::Refund; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Refund {}
crates/storage_impl/src/refund.rs
storage_impl::src::refund
51
true
// File: crates/storage_impl/src/business_profile.rs // Module: storage_impl::src::business_profile 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(), ) } }
crates/storage_impl/src/business_profile.rs
storage_impl::src::business_profile
3,455
true
// File: crates/storage_impl/src/invoice.rs // Module: storage_impl::src::invoice use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; pub use diesel_models::invoice::Invoice; use error_stack::{report, ResultExt}; pub use hyperswitch_domain_models::{ behaviour::Conversion, invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate}, merchant_key_store::MerchantKeyStore, }; use router_env::{instrument, tracing}; use crate::{ connection, errors::StorageError, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> InvoiceInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_new: DomainInvoice, ) -> CustomResult<DomainInvoice, StorageError> { let inv_new = invoice_new .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database(state, key_store, inv_new.insert(&conn)) .await } #[instrument(skip_all)] async fn find_invoice_by_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, ) -> CustomResult<DomainInvoice, StorageError> { let conn = connection::pg_connection_read(self).await?; self.call_database( state, key_store, Invoice::find_invoice_by_id_invoice_id(&conn, invoice_id), ) .await } #[instrument(skip_all)] async fn update_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, data: DomainInvoiceUpdate, ) -> CustomResult<DomainInvoice, StorageError> { let inv_new = data .construct_new() .await .change_context(StorageError::DecryptionError)?; let conn = connection::pg_connection_write(self).await?; self.call_database( state, key_store, Invoice::update_invoice_entry(&conn, invoice_id, inv_new), ) .await } #[instrument(skip_all)] async fn get_latest_invoice_for_subscription( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, ) -> CustomResult<DomainInvoice, StorageError> { let conn = connection::pg_connection_write(self).await?; let invoices: Vec<DomainInvoice> = self .find_resources( state, key_store, Invoice::list_invoices_by_subscription_id( &conn, subscription_id.clone(), Some(1), None, false, ), ) .await?; invoices .last() .cloned() .ok_or(report!(StorageError::ValueNotFound(format!( "Invoice not found for subscription_id: {}", subscription_id )))) } #[instrument(skip_all)] async fn find_invoice_by_subscription_id_connector_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<DomainInvoice>, StorageError> { let conn = connection::pg_connection_read(self).await?; self.find_optional_resource( state, key_store, Invoice::get_invoice_by_subscription_id_connector_invoice_id( &conn, subscription_id, connector_invoice_id, ), ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> InvoiceInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_new: DomainInvoice, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .insert_invoice_entry(state, key_store, invoice_new) .await } #[instrument(skip_all)] async fn find_invoice_by_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .find_invoice_by_invoice_id(state, key_store, invoice_id) .await } #[instrument(skip_all)] async fn update_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, data: DomainInvoiceUpdate, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .update_invoice_entry(state, key_store, invoice_id, data) .await } #[instrument(skip_all)] async fn get_latest_invoice_for_subscription( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, ) -> CustomResult<DomainInvoice, StorageError> { self.router_store .get_latest_invoice_for_subscription(state, key_store, subscription_id) .await } #[instrument(skip_all)] async fn find_invoice_by_subscription_id_connector_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<DomainInvoice>, StorageError> { self.router_store .find_invoice_by_subscription_id_connector_invoice_id( state, key_store, subscription_id, connector_invoice_id, ) .await } } #[async_trait::async_trait] impl InvoiceInterface for MockDb { type Error = StorageError; #[instrument(skip_all)] async fn insert_invoice_entry( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _invoice_new: DomainInvoice, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn find_invoice_by_invoice_id( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _invoice_id: String, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn update_invoice_entry( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _invoice_id: String, _data: DomainInvoiceUpdate, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn get_latest_invoice_for_subscription( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _subscription_id: String, ) -> CustomResult<DomainInvoice, StorageError> { Err(StorageError::MockDbError)? } async fn find_invoice_by_subscription_id_connector_invoice_id( &self, _state: &KeyManagerState, _key_store: &MerchantKeyStore, _subscription_id: String, _connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<DomainInvoice>, StorageError> { Err(StorageError::MockDbError)? } }
crates/storage_impl/src/invoice.rs
storage_impl::src::invoice
1,670
true
// File: crates/storage_impl/src/errors.rs // Module: storage_impl::src::errors 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, }
crates/storage_impl/src/errors.rs
storage_impl::src::errors
2,477
true
// File: crates/storage_impl/src/customers.rs // Module: storage_impl::src::customers use common_utils::{id_type, pii}; use diesel_models::{customers, kv}; use error_stack::ResultExt; use futures::future::try_join_all; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, customer as domain, merchant_key_store::MerchantKeyStore, }; use masking::PeekInterface; use router_env::{instrument, tracing}; use crate::{ diesel_error_to_data_error, errors::StorageError, kv_router_store, redis::kv_store::{decide_storage_scheme, KvStorePartition, Op, PartitionKey}, store::enums::MerchantStorageScheme, utils::{pg_connection_read, pg_connection_write}, CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, }; impl KvStorePartition for customers::Customer {} #[cfg(feature = "v2")] mod label { use common_utils::id_type; pub(super) const MODEL_NAME: &str = "customer_v2"; pub(super) const CLUSTER_LABEL: &str = "cust"; pub(super) fn get_global_id_label(global_customer_id: &id_type::GlobalCustomerId) -> String { format!( "customer_global_id_{}", global_customer_id.get_string_repr() ) } pub(super) fn get_merchant_scoped_id_label( merchant_id: &id_type::MerchantId, merchant_reference_id: &id_type::CustomerId, ) -> String { format!( "customer_mid_{}_mrefid_{}", merchant_id.get_string_repr(), merchant_reference_id.get_string_repr() ) } } #[async_trait::async_trait] impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_result = self .find_optional_resource_by_id( state, key_store, storage_scheme, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", customer_id.get_string_repr()), PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, ), ) .await?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(Some(customer)), }) } #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; self.find_optional_resource_by_id( state, key_store, storage_scheme, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", customer_id.get_string_repr()), PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, ), ) .await } #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_result = self .find_optional_resource_by_id( state, key_store, storage_scheme, customers::Customer::find_optional_by_merchant_id_merchant_reference_id( &conn, merchant_reference_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", merchant_reference_id.get_string_repr()), PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }, ), ) .await?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(Some(customer)), }) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(StorageError::EncryptionError)?; let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()); let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); self.update_resource( state, key_store, storage_scheme, customers::Customer::update_by_customer_id_merchant_id( &conn, customer_id.clone(), merchant_id.clone(), customer_update.clone().into(), ), updated_customer, kv_router_store::UpdateResourceParams { updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems { orig: customer.clone(), update_data: customer_update.clone().into(), }), operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()), }, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let result: domain::Customer = self .find_resource_by_id( state, key_store, storage_scheme, customers::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", merchant_reference_id.get_string_repr()), PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }, ), ) .await?; match result.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(result), } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let result: domain::Customer = self .find_resource_by_id( state, key_store, storage_scheme, customers::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), kv_router_store::FindResourceBy::Id( format!("cust_{}", customer_id.get_string_repr()), PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }, ), ) .await?; match result.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(result), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, StorageError> { self.router_store .list_customers_by_merchant_id(state, merchant_id, key_store, constraints) .await } #[instrument(skip_all)] async fn list_customers_by_merchant_id_with_count( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> { self.router_store .list_customers_by_merchant_id_with_count(state, merchant_id, key_store, constraints) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: domain::Customer, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let id = customer_data.id.clone(); let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let identifier = format!("cust_{}", id.get_string_repr()); let mut new_customer = customer_data .construct_new() .await .change_context(StorageError::EncryptionError)?; let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(decided_storage_scheme); let mut reverse_lookups = Vec::new(); if let Some(ref merchant_ref_id) = new_customer.merchant_reference_id { let reverse_lookup_merchant_scoped_id = label::get_merchant_scoped_id_label(&new_customer.merchant_id, merchant_ref_id); reverse_lookups.push(reverse_lookup_merchant_scoped_id); } self.insert_resource( state, key_store, decided_storage_scheme, new_customer.clone().insert(&conn), new_customer.clone().into(), kv_router_store::InsertResourceParams { insertable: kv::Insertable::Customer(new_customer.clone()), reverse_lookups, identifier, key, resource_type: "customer", }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: domain::Customer, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let key = PartitionKey::MerchantIdCustomerId { merchant_id: &customer_data.merchant_id.clone(), customer_id: &customer_data.customer_id.clone(), }; let identifier = format!("cust_{}", customer_data.customer_id.get_string_repr()); let mut new_customer = customer_data .construct_new() .await .change_context(StorageError::EncryptionError)?; let storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(storage_scheme); let customer = new_customer.clone().into(); self.insert_resource( state, key_store, storage_scheme, new_customer.clone().insert(&conn), customer, kv_router_store::InsertResourceParams { insertable: kv::Insertable::Customer(new_customer.clone()), reverse_lookups: vec![], identifier, key, resource_type: "customer", }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, StorageError> { self.router_store .delete_customer_by_customer_id_merchant_id(customer_id, merchant_id) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let result: domain::Customer = self .find_resource_by_id( state, key_store, storage_scheme, customers::Customer::find_by_global_id(&conn, id), kv_router_store::FindResourceBy::Id( format!("cust_{}", id.get_string_repr()), PartitionKey::GlobalId { id: id.get_string_repr(), }, ), ) .await?; if result.status == common_enums::DeleteStatus::Redacted { Err(StorageError::CustomerRedacted)? } else { Ok(result) } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(StorageError::EncryptionError)?; let database_call = customers::Customer::update_by_id(&conn, id.clone(), customer_update.clone().into()); let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); self.update_resource( state, key_store, storage_scheme, database_call, diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()), kv_router_store::UpdateResourceParams { updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems { orig: customer.clone(), update_data: customer_update.into(), }), operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()), }, ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_customer: Option<domain::Customer> = self .find_optional_resource( state, key_store, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), ) .await?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == pii::REDACTED) ...` match customer.name { Some(ref name) if name.peek() == pii::REDACTED => { Err(StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; self.find_optional_resource( state, key_store, customers::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), ) .await } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let maybe_customer: Option<domain::Customer> = self .find_optional_resource( state, key_store, customers::Customer::find_optional_by_merchant_id_merchant_reference_id( &conn, customer_id, merchant_id, ), ) .await?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == pii::REDACTED) ...` match customer.name { Some(ref name) if name.peek() == pii::REDACTED => { Err(StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, _customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; self.call_database( state, key_store, customers::Customer::update_by_customer_id_merchant_id( &conn, customer_id, merchant_id.clone(), customer_update.into(), ), ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let customer: domain::Customer = self .call_database( state, key_store, customers::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ), ) .await?; match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(customer), } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let customer: domain::Customer = self .call_database( state, key_store, customers::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ), ) .await?; match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(customer), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, StorageError> { let conn = pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); self.find_resources( state, key_store, customers::Customer::list_customers_by_merchant_id_and_constraints( &conn, merchant_id, customer_list_constraints, ), ) .await } #[instrument(skip_all)] async fn list_customers_by_merchant_id_with_count( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> { let conn = pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); let customers_constraints = diesel_models::query::customers::CustomerListConstraints { limit: customer_list_constraints.limit, offset: customer_list_constraints.offset, customer_id: customer_list_constraints.customer_id.clone(), time_range: customer_list_constraints.time_range, }; let customers = self .find_resources( state, key_store, customers::Customer::list_customers_by_merchant_id_and_constraints( &conn, merchant_id, customers_constraints, ), ) .await?; let total_count = customers::Customer::get_customer_count_by_merchant_id_and_constraints( &conn, merchant_id, customer_list_constraints, ) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) })?; Ok((customers, total_count)) } #[instrument(skip_all)] async fn insert_customer( &self, customer_data: domain::Customer, state: &KeyManagerState, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; let customer_new = customer_data .construct_new() .await .change_context(StorageError::EncryptionError)?; self.call_database(state, key_store, customer_new.insert(&conn)) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let conn = pg_connection_write(self).await?; customers::Customer::delete_by_customer_id_merchant_id(&conn, customer_id, merchant_id) .await .map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, _customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; self.call_database( state, key_store, customers::Customer::update_by_id(&conn, id.clone(), customer_update.into()), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_read(self).await?; let customer: domain::Customer = self .call_database( state, key_store, customers::Customer::find_by_global_id(&conn, id), ) .await?; match customer.name { Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?, _ => Ok(customer), } } } #[async_trait::async_trait] impl domain::CustomerInterface for MockDb { type Error = StorageError; #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let customers = self.customers.lock().await; self.find_resource(state, key_store, customers, |customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .await } #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { let customers = self.customers.lock().await; self.find_resource(state, key_store, customers, |customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .await } #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, _state: &KeyManagerState, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { todo!() } async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, StorageError> { let customers = self.customers.lock().await; let customers = try_join_all( customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .take(usize::from(constraints.limit)) .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0)) .map(|customer| async { customer .to_owned() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await?; Ok(customers) } async fn list_customers_by_merchant_id_with_count( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: domain::CustomerListConstraints, ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> { let customers = self.customers.lock().await; let customers_list = try_join_all( customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .take(usize::from(constraints.limit)) .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0)) .map(|customer| async { customer .to_owned() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }), ) .await?; let total_count = customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .count(); Ok((customers_list, total_count)) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, _state: &KeyManagerState, _customer_id: id_type::CustomerId, _merchant_id: id_type::MerchantId, _customer: domain::Customer, _customer_update: domain::CustomerUpdate, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_customer_by_customer_id_merchant_id( &self, _state: &KeyManagerState, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v2")] async fn find_customer_by_merchant_reference_id_merchant_id( &self, _state: &KeyManagerState, _merchant_reference_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[allow(clippy::panic)] async fn insert_customer( &self, customer_data: domain::Customer, state: &KeyManagerState, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let mut customers = self.customers.lock().await; let customer = Conversion::convert(customer_data) .await .change_context(StorageError::EncryptionError)?; customers.push(customer.clone()); customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v1")] async fn delete_customer_by_customer_id_merchant_id( &self, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, _customer: domain::Customer, _customer_update: domain::CustomerUpdate, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v2")] async fn find_customer_by_global_id( &self, _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } }
crates/storage_impl/src/customers.rs
storage_impl::src::customers
7,570
true
// File: crates/storage_impl/src/kv_router_store.rs // Module: storage_impl::src::kv_router_store use std::{fmt::Debug, sync::Arc}; use common_enums::enums::MerchantStorageScheme; use common_utils::{fallback_reverse_lookup_not_found, types::keymanager::KeyManagerState}; use diesel_models::{errors::DatabaseError, kv}; use error_stack::ResultExt; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::StrongSecret; use redis_interface::{errors::RedisError, types::HsetnxReply, RedisConnectionPool}; use router_env::logger; use serde::de; #[cfg(not(feature = "payouts"))] pub use crate::database::store::Store; pub use crate::{database::store::DatabaseStore, mock_db::MockDb}; use crate::{ database::store::PgPool, diesel_error_to_data_error, errors::{self, RedisErrorExt, StorageResult}, lookup::ReverseLookupInterface, metrics, redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, KvStorePartition, Op, PartitionKey, RedisConnInterface, }, utils::{find_all_combined_kv_database, try_redis_get_else_try_database_get}, RouterStore, TenantConfig, UniqueConstraints, }; #[derive(Debug, Clone)] pub struct KVRouterStore<T: DatabaseStore> { pub router_store: RouterStore<T>, drainer_stream_name: String, drainer_num_partitions: u8, pub ttl_for_kv: u32, pub request_id: Option<String>, pub soft_kill_mode: bool, } pub struct InsertResourceParams<'a> { pub insertable: kv::Insertable, pub reverse_lookups: Vec<String>, pub key: PartitionKey<'a>, // secondary key pub identifier: String, // type of resource Eg: "payment_attempt" pub resource_type: &'static str, } pub struct UpdateResourceParams<'a> { pub updateable: kv::Updateable, pub operation: Op<'a>, } pub struct FilterResourceParams<'a> { pub key: PartitionKey<'a>, pub pattern: &'static str, pub limit: Option<i64>, } pub enum FindResourceBy<'a> { Id(String, PartitionKey<'a>), LookupId(String), } pub trait DomainType: Debug + Sync + Conversion {} impl<T: Debug + Sync + Conversion> DomainType for T {} /// Storage model with all required capabilities for KV operations pub trait StorageModel<D: Conversion>: de::DeserializeOwned + serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync + Send + ReverseConversion<D> { } impl<T, D> StorageModel<D> for T where T: de::DeserializeOwned + serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync + Send + ReverseConversion<D>, D: DomainType, { } #[async_trait::async_trait] impl<T> DatabaseStore for KVRouterStore<T> where RouterStore<T>: DatabaseStore, T: DatabaseStore, { type Config = (RouterStore<T>, String, u8, u32, Option<bool>); async fn new( config: Self::Config, tenant_config: &dyn TenantConfig, _test_transaction: bool, ) -> StorageResult<Self> { let (router_store, _, drainer_num_partitions, ttl_for_kv, soft_kill_mode) = config; let drainer_stream_name = format!("{}_{}", tenant_config.get_schema(), config.1); Ok(Self::from_store( router_store, drainer_stream_name, drainer_num_partitions, ttl_for_kv, soft_kill_mode, )) } fn get_master_pool(&self) -> &PgPool { self.router_store.get_master_pool() } fn get_replica_pool(&self) -> &PgPool { self.router_store.get_replica_pool() } fn get_accounts_master_pool(&self) -> &PgPool { self.router_store.get_accounts_master_pool() } fn get_accounts_replica_pool(&self) -> &PgPool { self.router_store.get_accounts_replica_pool() } } impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> { fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> { self.router_store.get_redis_conn() } } impl<T: DatabaseStore> KVRouterStore<T> { pub fn from_store( store: RouterStore<T>, drainer_stream_name: String, drainer_num_partitions: u8, ttl_for_kv: u32, soft_kill: Option<bool>, ) -> Self { let request_id = store.request_id.clone(); Self { router_store: store, drainer_stream_name, drainer_num_partitions, ttl_for_kv, request_id, soft_kill_mode: soft_kill.unwrap_or(false), } } pub fn master_key(&self) -> &StrongSecret<Vec<u8>> { self.router_store.master_key() } pub fn get_drainer_stream_name(&self, shard_key: &str) -> String { format!("{{{}}}_{}", shard_key, self.drainer_stream_name) } pub async fn push_to_drainer_stream<R>( &self, redis_entry: kv::TypedSql, partition_key: PartitionKey<'_>, ) -> error_stack::Result<(), RedisError> where R: KvStorePartition, { let global_id = format!("{partition_key}"); let request_id = self.request_id.clone().unwrap_or_default(); let shard_key = R::shard_key(partition_key, self.drainer_num_partitions); let stream_name = self.get_drainer_stream_name(&shard_key); self.router_store .cache_store .redis_conn .stream_append_entry( &stream_name.into(), &redis_interface::RedisEntryId::AutoGeneratedID, redis_entry .to_field_value_pairs(request_id, global_id) .change_context(RedisError::JsonSerializationFailed)?, ) .await .map(|_| metrics::KV_PUSHED_TO_DRAINER.add(1, &[])) .inspect_err(|error| { metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(1, &[]); logger::error!(?error, "Failed to add entry in drainer stream"); }) .change_context(RedisError::StreamAppendFailed) } pub async fn find_resource_by_id<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, find_resource_db_fut: R, find_by: FindResourceBy<'_>, ) -> error_stack::Result<D, errors::StorageError> where D: DomainType, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send, { let database_call = || async { find_resource_db_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<T, M>( self, storage_scheme, Op::Find, )) .await; let res = || async { match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let (field, key) = match find_by { FindResourceBy::Id(field, key) => (field, key), FindResourceBy::LookupId(lookup_id) => { let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); ( lookup.clone().sk_id, PartitionKey::CombinationKey { combination: &lookup.clone().pk_id, }, ) } }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key)) .await? .try_into_hget() }, database_call, )) .await } } }; res() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } pub async fn find_optional_resource_by_id<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, find_resource_db_fut: R, find_by: FindResourceBy<'_>, ) -> error_stack::Result<Option<D>, errors::StorageError> where D: DomainType, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<Option<M>, DatabaseError>> + Send, { let database_call = || async { find_resource_db_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<T, M>( self, storage_scheme, Op::Find, )) .await; let res = || async { match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let (field, key) = match find_by { FindResourceBy::Id(field, key) => (field, key), FindResourceBy::LookupId(lookup_id) => { let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); ( lookup.clone().sk_id, PartitionKey::CombinationKey { combination: &lookup.clone().pk_id, }, ) } }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key)) .await? .try_into_hget() .map(Some) }, database_call, )) .await } } }; match res().await? { Some(resource) => Ok(Some( resource .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, )), None => Ok(None), } } pub async fn insert_resource<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, create_resource_fut: R, resource_new: M, InsertResourceParams { insertable, reverse_lookups, key, identifier, resource_type, }: InsertResourceParams<'_>, ) -> error_stack::Result<D, errors::StorageError> where D: Debug + Sync + Conversion, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send, { let storage_scheme = Box::pin(decide_storage_scheme::<_, M>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => create_resource_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }), MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew { sk_id: identifier.clone(), pk_id: key_str.clone(), lookup_id: v, source: resource_type.to_string(), updated_by: storage_scheme.to_string(), }; let results = reverse_lookups .into_iter() .map(|v| self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme)); futures::future::try_join_all(results).await?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(insertable), }, }; match Box::pin(kv_wrapper::<M, _, _>( self, KvOperation::<M>::HSetNx(&identifier, &resource_new, redis_entry), key.clone(), )) .await .map_err(|err| err.to_redis_failed_response(&key.to_string()))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: resource_type, key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(resource_new), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } }? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } pub async fn update_resource<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, update_resource_fut: R, updated_resource: M, UpdateResourceParams { updateable, operation, }: UpdateResourceParams<'_>, ) -> error_stack::Result<D, errors::StorageError> where D: Debug + Sync + Conversion, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send, { match operation { Op::Update(key, field, updated_by) => { let storage_scheme = Box::pin(decide_storage_scheme::<_, M>( self, storage_scheme, Op::Update(key.clone(), field, updated_by), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { update_resource_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let redis_value = serde_json::to_string(&updated_resource) .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(updateable), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<M>::Hset((field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_resource) } } } _ => Err(errors::StorageError::KVError.into()), }? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } pub async fn filter_resources<D, R, M>( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, filter_resource_db_fut: R, filter_fn: impl Fn(&M) -> bool, FilterResourceParams { key, pattern, limit, }: FilterResourceParams<'_>, ) -> error_stack::Result<Vec<D>, errors::StorageError> where D: Debug + Sync + Conversion, M: StorageModel<D>, R: futures::Future<Output = error_stack::Result<Vec<M>, DatabaseError>> + Send, { let db_call = || async { filter_resource_db_fut.await.map_err(|error| { let new_err = diesel_error_to_data_error(*error.current_context()); error.change_context(new_err) }) }; let resources = match storage_scheme { MerchantStorageScheme::PostgresOnly => db_call().await, MerchantStorageScheme::RedisKv => { let redis_fut = async { let kv_result = Box::pin(kv_wrapper::<M, _, _>( self, KvOperation::<M>::Scan(pattern), key, )) .await? .try_into_scan(); kv_result.map(|records| records.into_iter().filter(filter_fn).collect()) }; Box::pin(find_all_combined_kv_database(redis_fut, db_call, limit)).await } }?; let resource_futures = resources .into_iter() .map(|pm| async { pm.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .collect::<Vec<_>>(); futures::future::try_join_all(resource_futures).await } } #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {} #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {}
crates/storage_impl/src/kv_router_store.rs
storage_impl::src::kv_router_store
3,932
true
// File: crates/storage_impl/src/merchant_key_store.rs // Module: storage_impl::src::merchant_key_store use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store as domain, merchant_key_store::MerchantKeyStoreInterface, }; use masking::Secret; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use crate::redis::{ cache, cache::{CacheKind, ACCOUNTS_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> MerchantKeyStoreInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { self.router_store .insert_merchant_key_store(state, merchant_key_store, key) .await } #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { self.router_store .get_merchant_key_store_by_merchant_id(state, merchant_id, key) .await } #[instrument(skip_all)] async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error> { self.router_store .delete_merchant_key_store_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { self.router_store .list_multiple_key_stores(state, merchant_ids, key) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { self.router_store .get_all_key_stores(state, key, from, to) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { let conn = pg_accounts_connection_write(self).await?; let merchant_id = merchant_key_store.merchant_id.clone(); merchant_key_store .construct_new() .await .change_context(Self::Error::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(Self::Error::from(error)))? .convert(state, key, merchant_id.into()) .await .change_context(Self::Error::DecryptionError) } #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { let fetch_func = || async { let conn = pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(Self::Error::DecryptionError) } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::get_or_populate_in_memory( self, &key_store_cache_key, fetch_func, &ACCOUNTS_CACHE, ) .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(Self::Error::DecryptionError) } } #[instrument(skip_all)] async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error> { let delete_func = || async { let conn = pg_accounts_connection_write(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(Self::Error::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { delete_func().await } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::publish_and_redact( self, CacheKind::Accounts(key_store_cache_key.into()), delete_func, ) .await } } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { let fetch_func = || async { let conn = pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores( &conn, merchant_ids, ) .await .map_err(|error| report!(Self::Error::from(error))) }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert(state, key, merchant_id.into()) .await .change_context(Self::Error::DecryptionError) })) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> { let conn = pg_accounts_connection_read(self).await?; let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores( &conn, from, to, ) .await .map_err(|err| report!(Self::Error::from(err)))?; futures::future::try_join_all(stores.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert(state, key, merchant_id.into()) .await .change_context(Self::Error::DecryptionError) })) .await } } #[async_trait::async_trait] impl MerchantKeyStoreInterface for MockDb { type Error = StorageError; async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { let mut locked_merchant_key_store = self.merchant_key_store.lock().await; if locked_merchant_key_store .iter() .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id) { Err(StorageError::DuplicateValue { entity: "merchant_key_store", key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()), })?; } let merchant_key = Conversion::convert(merchant_key_store) .await .change_context(StorageError::MockDbError)?; locked_merchant_key_store.push(merchant_key.clone()); let merchant_id = merchant_key.merchant_id.clone(); merchant_key .convert(state, key, merchant_id.into()) .await .change_context(StorageError::DecryptionError) } async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, StorageError> { self.merchant_key_store .lock() .await .iter() .find(|merchant_key| merchant_key.merchant_id == *merchant_id) .cloned() .ok_or(StorageError::ValueNotFound(String::from( "merchant_key_store", )))? .convert(state, key, merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError) } async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut merchant_key_stores = self.merchant_key_store.lock().await; let index = merchant_key_stores .iter() .position(|mks| mks.merchant_id == *merchant_id) .ok_or(StorageError::ValueNotFound(format!( "No merchant key store found for merchant_id = {merchant_id:?}", )))?; merchant_key_stores.remove(index); Ok(true) } #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all( merchant_key_stores .iter() .filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id)) .map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError) }), ) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, _from: u32, _to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError) })) .await } }
crates/storage_impl/src/merchant_key_store.rs
storage_impl::src::merchant_key_store
2,648
true
// File: crates/storage_impl/src/reverse_lookup.rs // Module: storage_impl::src::reverse_lookup use diesel_models::reverse_lookup::ReverseLookup; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for ReverseLookup {}
crates/storage_impl/src/reverse_lookup.rs
storage_impl::src::reverse_lookup
54
true
// File: crates/storage_impl/src/connection.rs // Module: storage_impl::src::connection use bb8::PooledConnection; use common_utils::errors; use diesel::PgConnection; use error_stack::ResultExt; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; /// Creates a Redis connection pool for the specified Redis settings /// # Panics /// /// Panics if failed to create a redis pool #[allow(clippy::expect_used)] pub async fn redis_connection( redis: &redis_interface::RedisSettings, ) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(redis) .await .expect("Failed to create Redis Connection Pool") } pub async fn pg_connection_read<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::errors::StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_master_pool(); pool.get() .await .change_context(crate::errors::StorageError::DatabaseConnectionError) } pub async fn pg_connection_write<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(crate::errors::StorageError::DatabaseConnectionError) }
crates/storage_impl/src/connection.rs
storage_impl::src::connection
517
true
// File: crates/storage_impl/src/mandate.rs // Module: storage_impl::src::mandate use diesel_models::Mandate; use crate::redis::kv_store::KvStorePartition; impl KvStorePartition for Mandate {}
crates/storage_impl/src/mandate.rs
storage_impl::src::mandate
52
true
// File: crates/storage_impl/src/utils.rs // Module: storage_impl::src::utils use bb8::PooledConnection; use diesel::PgConnection; use error_stack::ResultExt; use crate::{ errors::{RedisErrorExt, StorageError}, metrics, DatabaseStore, }; pub async fn pg_connection_read<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) } pub async fn pg_connection_write<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_read<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_accounts_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) } pub async fn pg_accounts_connection_write<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_accounts_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) } pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>( redis_fut: RFut, database_call_closure: F, ) -> error_stack::Result<T, StorageError> where F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<T, StorageError>>, { let redis_output = redis_fut.await; match redis_output { Ok(output) => Ok(output), Err(redis_error) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call_closure().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } } use std::collections::HashSet; use crate::UniqueConstraints; fn union_vec<T>(mut kv_rows: Vec<T>, sql_rows: Vec<T>) -> Vec<T> where T: UniqueConstraints, { let mut kv_unique_keys = HashSet::new(); kv_rows.iter().for_each(|v| { kv_unique_keys.insert(v.unique_constraints().concat()); }); sql_rows.into_iter().for_each(|v| { let unique_key = v.unique_constraints().concat(); if !kv_unique_keys.contains(&unique_key) { kv_rows.push(v); } }); kv_rows } pub async fn find_all_combined_kv_database<F, RFut, DFut, T>( redis_fut: RFut, database_call: F, limit: Option<i64>, ) -> error_stack::Result<Vec<T>, StorageError> where T: UniqueConstraints, F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<Vec<T>, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<Vec<T>, StorageError>>, { let trunc = |v: &mut Vec<_>| { if let Some(l) = limit.and_then(|v| TryInto::try_into(v).ok()) { v.truncate(l); } }; let limit_satisfies = |len: usize, limit: i64| { TryInto::try_into(limit) .ok() .is_none_or(|val: usize| len >= val) }; let redis_output = redis_fut.await; match (redis_output, limit) { (Ok(mut kv_rows), Some(lim)) if limit_satisfies(kv_rows.len(), lim) => { trunc(&mut kv_rows); Ok(kv_rows) } (Ok(kv_rows), _) => database_call().await.map(|db_rows| { let mut res = union_vec(kv_rows, db_rows); trunc(&mut res); res }), (Err(redis_error), _) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } }
crates/storage_impl/src/utils.rs
storage_impl::src::utils
1,428
true
// File: crates/storage_impl/src/redis.rs // Module: storage_impl::src::redis pub mod cache; pub mod kv_store; pub mod pub_sub; use std::sync::{atomic, Arc}; use router_env::tracing::Instrument; use self::{kv_store::RedisConnInterface, pub_sub::PubSubInterface}; #[derive(Clone)] pub struct RedisStore { // Maybe expose the redis_conn via traits instead of the making the field public pub(crate) redis_conn: Arc<redis_interface::RedisConnectionPool>, } impl std::fmt::Debug for RedisStore { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CacheStore") .field("redis_conn", &"Redis conn doesn't implement debug") .finish() } } impl RedisStore { pub async fn new( conf: &redis_interface::RedisSettings, ) -> error_stack::Result<Self, redis_interface::errors::RedisError> { Ok(Self { redis_conn: Arc::new(redis_interface::RedisConnectionPool::new(conf).await?), }) } pub fn set_error_callback(&self, callback: tokio::sync::oneshot::Sender<()>) { let redis_clone = self.redis_conn.clone(); let _task_handle = tokio::spawn( async move { redis_clone.on_error(callback).await; } .in_current_span(), ); } } impl RedisConnInterface for RedisStore { fn get_redis_conn( &self, ) -> error_stack::Result< Arc<redis_interface::RedisConnectionPool>, redis_interface::errors::RedisError, > { if self .redis_conn .is_redis_available .load(atomic::Ordering::SeqCst) { Ok(self.redis_conn.clone()) } else { Err(redis_interface::errors::RedisError::RedisConnectionError.into()) } } }
crates/storage_impl/src/redis.rs
storage_impl::src::redis
425
true
// File: crates/storage_impl/src/database/store.rs // Module: storage_impl::src::database::store use async_bb8_diesel::{AsyncConnection, ConnectionError}; use bb8::CustomizeConnection; use common_utils::{types::TenantConfig, DbConnectionParams}; use diesel::PgConnection; use error_stack::ResultExt; use crate::{ config::Database, errors::{StorageError, StorageResult}, }; pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; #[async_trait::async_trait] pub trait DatabaseStore: Clone + Send + Sync { type Config: Send; async fn new( config: Self::Config, tenant_config: &dyn TenantConfig, test_transaction: bool, ) -> StorageResult<Self>; fn get_master_pool(&self) -> &PgPool; fn get_replica_pool(&self) -> &PgPool; fn get_accounts_master_pool(&self) -> &PgPool; fn get_accounts_replica_pool(&self) -> &PgPool; } #[derive(Debug, Clone)] pub struct Store { pub master_pool: PgPool, pub accounts_pool: PgPool, } #[async_trait::async_trait] impl DatabaseStore for Store { type Config = Database; async fn new( config: Database, tenant_config: &dyn TenantConfig, test_transaction: bool, ) -> StorageResult<Self> { Ok(Self { master_pool: diesel_make_pg_pool(&config, tenant_config.get_schema(), test_transaction) .await?, accounts_pool: diesel_make_pg_pool( &config, tenant_config.get_accounts_schema(), test_transaction, ) .await?, }) } fn get_master_pool(&self) -> &PgPool { &self.master_pool } fn get_replica_pool(&self) -> &PgPool { &self.master_pool } fn get_accounts_master_pool(&self) -> &PgPool { &self.accounts_pool } fn get_accounts_replica_pool(&self) -> &PgPool { &self.accounts_pool } } #[derive(Debug, Clone)] pub struct ReplicaStore { pub master_pool: PgPool, pub replica_pool: PgPool, pub accounts_master_pool: PgPool, pub accounts_replica_pool: PgPool, } #[async_trait::async_trait] impl DatabaseStore for ReplicaStore { type Config = (Database, Database); async fn new( config: (Database, Database), tenant_config: &dyn TenantConfig, test_transaction: bool, ) -> StorageResult<Self> { let (master_config, replica_config) = config; let master_pool = diesel_make_pg_pool(&master_config, tenant_config.get_schema(), test_transaction) .await .attach_printable("failed to create master pool")?; let accounts_master_pool = diesel_make_pg_pool( &master_config, tenant_config.get_accounts_schema(), test_transaction, ) .await .attach_printable("failed to create accounts master pool")?; let replica_pool = diesel_make_pg_pool( &replica_config, tenant_config.get_schema(), test_transaction, ) .await .attach_printable("failed to create replica pool")?; let accounts_replica_pool = diesel_make_pg_pool( &replica_config, tenant_config.get_accounts_schema(), test_transaction, ) .await .attach_printable("failed to create accounts pool")?; Ok(Self { master_pool, replica_pool, accounts_master_pool, accounts_replica_pool, }) } fn get_master_pool(&self) -> &PgPool { &self.master_pool } fn get_replica_pool(&self) -> &PgPool { &self.replica_pool } fn get_accounts_master_pool(&self) -> &PgPool { &self.accounts_master_pool } fn get_accounts_replica_pool(&self) -> &PgPool { &self.accounts_replica_pool } } pub async fn diesel_make_pg_pool( database: &Database, schema: &str, test_transaction: bool, ) -> StorageResult<PgPool> { let database_url = database.get_database_url(schema); let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url); let mut pool = bb8::Pool::builder() .max_size(database.pool_size) .min_idle(database.min_idle) .queue_strategy(database.queue_strategy.into()) .connection_timeout(std::time::Duration::from_secs(database.connection_timeout)) .max_lifetime(database.max_lifetime.map(std::time::Duration::from_secs)); if test_transaction { pool = pool.connection_customizer(Box::new(TestTransaction)); } pool.build(manager) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to create PostgreSQL connection pool") } #[derive(Debug)] struct TestTransaction; #[async_trait::async_trait] impl CustomizeConnection<PgPooledConn, ConnectionError> for TestTransaction { #[allow(clippy::unwrap_used)] async fn on_acquire(&self, conn: &mut PgPooledConn) -> Result<(), ConnectionError> { use diesel::Connection; conn.run(|conn| { conn.begin_test_transaction().unwrap(); Ok(()) }) .await } }
crates/storage_impl/src/database/store.rs
storage_impl::src::database::store
1,176
true
// File: crates/storage_impl/src/payments/payment_attempt.rs // Module: storage_impl::src::payments::payment_attempt use common_utils::errors::CustomResult; #[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; #[cfg(feature = "v1")] use common_utils::{ fallback_reverse_lookup_not_found, types::{ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy}, }; #[cfg(feature = "v1")] use diesel_models::payment_attempt::PaymentAttemptNew as DieselPaymentAttemptNew; use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, MandateDetails as DieselMandateDetails, MerchantStorageScheme, }, kv, payment_attempt::PaymentAttempt as DieselPaymentAttempt, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; #[cfg(feature = "v2")] use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; use hyperswitch_domain_models::{ mandates::{MandateAmountData, MandateDataType, MandateDetails}, payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate}, }; #[cfg(all(feature = "v1", feature = "olap"))] use hyperswitch_domain_models::{ payments::payment_attempt::PaymentListFilters, payments::PaymentIntent, }; #[cfg(feature = "v2")] use label::*; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; #[cfg(feature = "v2")] use crate::kv_router_store::{FilterResourceParams, FindResourceBy, UpdateResourceParams}; use crate::{ diesel_error_to_data_error, errors, errors::RedisErrorExt, kv_router_store::KVRouterStore, lookup::ReverseLookupInterface, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get}, DataModelExt, DatabaseStore, RouterStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { type Error = errors::StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttemptNew, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; payment_attempt .to_storage_model() .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, payment_attempt: PaymentAttempt, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; payment_attempt .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| { let new_error = diesel_error_to_data_error(*error.current_context()); error.change_context(new_error) })? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; this.to_storage_model() .update_with_attempt_id(&conn, payment_attempt.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)? .update_with_attempt_id( &conn, diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt), ) .await .map_err(|error| { let new_error = diesel_error_to_data_error(*error.current_context()); error.change_context(new_error) })? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &ConnectorTransactionId, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_connector_transaction_id_payment_id_merchant_id( &conn, connector_transaction_id, payment_id, merchant_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id( &conn, payment_id, merchant_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &conn, payment_id, merchant_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, payment_id: &common_utils::id_type::GlobalPaymentId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id( &conn, payment_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_merchant_id_connector_txn_id( &conn, merchant_id, connector_txn_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_txn_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_profile_id_connector_transaction_id( &conn, profile_id, connector_txn_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_payment_id_merchant_id_attempt_id( &conn, payment_id, merchant_id, attempt_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filters_for_payments( &self, pi: &[PaymentIntent], merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentListFilters, errors::StorageError> { use hyperswitch_domain_models::behaviour::Conversion; let conn = pg_connection_read(self).await?; let intents = futures::future::try_join_all(pi.iter().cloned().map(|pi| async { Conversion::convert(pi) .await .change_context(errors::StorageError::EncryptionError) })) .await?; DieselPaymentAttempt::get_filters_for_payments(&conn, intents.as_slice(), merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( |( connector, currency, status, payment_method, payment_method_type, authentication_type, )| PaymentListFilters { connector, currency, status, payment_method, payment_method_type, authentication_type, }, ) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_merchant_id_preprocessing_id( &conn, merchant_id, preprocessing_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(|a| { a.into_iter() .map(PaymentAttempt::from_storage_model) .collect() }) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, attempt_id: &common_utils::id_type::GlobalAttemptId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_id(&conn, attempt_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempts_by_payment_intent_id( &self, key_manager_state: &KeyManagerState, payment_id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> { use common_utils::ext_traits::AsyncExt; let conn = pg_connection_read(self).await?; DieselPaymentAttempt::find_by_payment_id(&conn, payment_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_and_then(|payment_attempts| async { let mut domain_payment_attempts = Vec::with_capacity(payment_attempts.len()); for attempt in payment_attempts.into_iter() { domain_payment_attempts.push( attempt .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_payment_attempts) }) .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method: Option<Vec<common_enums::PaymentMethod>>, payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, card_discovery: Option<Vec<common_enums::CardDiscovery>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = self .db_store .get_replica_pool() .get() .await .change_context(errors::StorageError::DatabaseConnectionError)?; let connector_strings = connector.as_ref().map(|connector| { connector .iter() .map(|c| c.to_string()) .collect::<Vec<String>>() }); DieselPaymentAttempt::get_total_count_of_attempts( &conn, merchant_id, active_attempt_ids, connector_strings, payment_method, payment_method_type, authentication_type, merchant_connector_id, card_network, card_discovery, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method_type: Option<Vec<common_enums::PaymentMethod>>, payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = self .db_store .get_replica_pool() .get() .await .change_context(errors::StorageError::DatabaseConnectionError)?; DieselPaymentAttempt::get_total_count_of_attempts( &conn, merchant_id, active_attempt_ids, connector .as_ref() .map(|vals| vals.iter().map(|v| v.to_string()).collect()), payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, card_network, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { type Error = errors::StorageError; #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttemptNew, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_attempt(payment_attempt, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let merchant_id = payment_attempt.merchant_id.clone(); let payment_id = payment_attempt.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let key_str = key.to_string(); let created_attempt = PaymentAttempt { payment_id: payment_attempt.payment_id.clone(), merchant_id: payment_attempt.merchant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, net_amount: payment_attempt.net_amount.clone(), currency: payment_attempt.currency, save_to_locker: payment_attempt.save_to_locker, connector: payment_attempt.connector.clone(), error_message: payment_attempt.error_message.clone(), offer_amount: payment_attempt.offer_amount, payment_method_id: payment_attempt.payment_method_id.clone(), payment_method: payment_attempt.payment_method, connector_transaction_id: None, capture_method: payment_attempt.capture_method, capture_on: payment_attempt.capture_on, confirm: payment_attempt.confirm, authentication_type: payment_attempt.authentication_type, created_at: payment_attempt .created_at .unwrap_or_else(common_utils::date_time::now), modified_at: payment_attempt .created_at .unwrap_or_else(common_utils::date_time::now), last_synced: payment_attempt.last_synced, amount_to_capture: payment_attempt.amount_to_capture, cancellation_reason: payment_attempt.cancellation_reason.clone(), mandate_id: payment_attempt.mandate_id.clone(), browser_info: payment_attempt.browser_info.clone(), payment_token: payment_attempt.payment_token.clone(), error_code: payment_attempt.error_code.clone(), connector_metadata: payment_attempt.connector_metadata.clone(), payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, payment_method_data: payment_attempt.payment_method_data.clone(), business_sub_label: payment_attempt.business_sub_label.clone(), straight_through_algorithm: payment_attempt.straight_through_algorithm.clone(), mandate_details: payment_attempt.mandate_details.clone(), preprocessing_step_id: payment_attempt.preprocessing_step_id.clone(), error_reason: payment_attempt.error_reason.clone(), multiple_capture_count: payment_attempt.multiple_capture_count, connector_response_reference_id: None, charge_id: None, amount_capturable: payment_attempt.amount_capturable, updated_by: storage_scheme.to_string(), authentication_data: payment_attempt.authentication_data.clone(), encoded_data: payment_attempt.encoded_data.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), unified_code: payment_attempt.unified_code.clone(), unified_message: payment_attempt.unified_message.clone(), external_three_ds_authentication_attempted: payment_attempt .external_three_ds_authentication_attempted, authentication_connector: payment_attempt.authentication_connector.clone(), authentication_id: payment_attempt.authentication_id.clone(), mandate_data: payment_attempt.mandate_data.clone(), payment_method_billing_address_id: payment_attempt .payment_method_billing_address_id .clone(), fingerprint_id: payment_attempt.fingerprint_id.clone(), client_source: payment_attempt.client_source.clone(), client_version: payment_attempt.client_version.clone(), customer_acceptance: payment_attempt.customer_acceptance.clone(), organization_id: payment_attempt.organization_id.clone(), profile_id: payment_attempt.profile_id.clone(), connector_mandate_detail: payment_attempt.connector_mandate_detail.clone(), request_extended_authorization: payment_attempt.request_extended_authorization, extended_authorization_applied: payment_attempt.extended_authorization_applied, capture_before: payment_attempt.capture_before, card_discovery: payment_attempt.card_discovery, charges: None, issuer_error_code: None, issuer_error_message: None, processor_merchant_id: payment_attempt.processor_merchant_id.clone(), created_by: payment_attempt.created_by.clone(), setup_future_usage_applied: payment_attempt.setup_future_usage_applied, routing_approach: payment_attempt.routing_approach.clone(), connector_request_reference_id: payment_attempt .connector_request_reference_id .clone(), debit_routing_savings: None, network_transaction_id: payment_attempt.network_transaction_id.clone(), is_overcapture_enabled: None, network_details: payment_attempt.network_details.clone(), is_stored_credential: payment_attempt.is_stored_credential, authorized_amount: payment_attempt.authorized_amount, }; let field = format!("pa_{}", created_attempt.attempt_id); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new( payment_attempt.to_storage_model(), ))), }, }; //Reverse lookup for attempt_id let reverse_lookup = ReverseLookupNew { lookup_id: format!( "pa_{}_{}", created_attempt.merchant_id.get_string_repr(), &created_attempt.attempt_id, ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payment_attempt".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; match Box::pin(kv_wrapper::<PaymentAttempt, _, _>( self, KvOperation::HSetNx( &field, &created_attempt.clone().to_storage_model(), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "payment attempt", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_attempt), Err(error) => Err(error.change_context(errors::StorageError::KVError)), } } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, payment_attempt: PaymentAttempt, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Insert, )) .await; match decided_storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_attempt( key_manager_state, merchant_key_store, payment_attempt, decided_storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalPaymentId { id: &payment_attempt.payment_id, }; let key_str = key.to_string(); let field = format!( "{}_{}", label::CLUSTER_LABEL, payment_attempt.id.get_string_repr() ); let diesel_payment_attempt_new = payment_attempt .clone() .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let diesel_payment_attempt_for_redis: DieselPaymentAttempt = Conversion::convert(payment_attempt.clone()) .await .change_context(errors::StorageError::EncryptionError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new( diesel_payment_attempt_new.clone(), ))), }, }; let reverse_lookup_attempt_id = ReverseLookupNew { lookup_id: label::get_global_id_label(&payment_attempt.id), pk_id: key_str.clone(), sk_id: field.clone(), source: "payment_attempt".to_string(), updated_by: decided_storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup_attempt_id, decided_storage_scheme) .await?; if let Some(ref conn_txn_id_val) = payment_attempt.connector_payment_id { let reverse_lookup_conn_txn_id = ReverseLookupNew { lookup_id: label::get_profile_id_connector_transaction_label( payment_attempt.profile_id.get_string_repr(), conn_txn_id_val, ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payment_attempt".to_string(), updated_by: decided_storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup_conn_txn_id, decided_storage_scheme) .await?; } match Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>( self, KvOperation::HSetNx(&field, &diesel_payment_attempt_for_redis, redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "payment_attempt", key: Some(payment_attempt.id.get_string_repr().to_owned()), } .into()), Ok(HsetnxReply::KeySet) => Ok(payment_attempt), Err(error) => Err(error.change_context(errors::StorageError::KVError)), } } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let key = PartitionKey::MerchantIdPaymentId { merchant_id: &this.merchant_id, payment_id: &this.payment_id, }; let field = format!("pa_{}", this.attempt_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_attempt_with_attempt_id(this, payment_attempt, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let old_connector_transaction_id = &this.get_connector_payment_id(); let old_preprocessing_id = &this.preprocessing_step_id; let updated_attempt = PaymentAttempt::from_storage_model( payment_attempt .clone() .to_storage_model() .apply_changeset(this.clone().to_storage_model()), ); // Check for database presence as well Maybe use a read replica here ? let redis_value = serde_json::to_string(&updated_attempt) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PaymentAttemptUpdate(Box::new( kv::PaymentAttemptUpdateMems { orig: this.clone().to_storage_model(), update_data: payment_attempt.to_storage_model(), }, ))), }, }; match ( old_connector_transaction_id, &updated_attempt.get_connector_payment_id(), ) { (None, Some(connector_transaction_id)) => { add_connector_txn_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), connector_transaction_id, storage_scheme, ) .await?; } (Some(old_connector_transaction_id), Some(connector_transaction_id)) => { if old_connector_transaction_id.ne(connector_transaction_id) { add_connector_txn_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), connector_transaction_id, storage_scheme, ) .await?; } } (_, _) => {} } match (old_preprocessing_id, &updated_attempt.preprocessing_step_id) { (None, Some(preprocessing_id)) => { add_preprocessing_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), preprocessing_id.as_str(), storage_scheme, ) .await?; } (Some(old_preprocessing_id), Some(preprocessing_id)) => { if old_preprocessing_id.ne(preprocessing_id) { add_preprocessing_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), preprocessing_id.as_str(), storage_scheme, ) .await?; } } (_, _) => {} } Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<DieselPaymentAttempt>((&field, redis_value), redis_entry), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_attempt) } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, this: PaymentAttempt, payment_attempt_update: PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let payment_attempt = Conversion::convert(this.clone()) .await .change_context(errors::StorageError::DecryptionError)?; let key = PartitionKey::GlobalPaymentId { id: &this.payment_id, }; let field = format!("{}_{}", label::CLUSTER_LABEL, this.id.get_string_repr()); let conn = pg_connection_write(self).await?; let payment_attempt_internal = diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt_update); let updated_payment_attempt = payment_attempt_internal .clone() .apply_changeset(payment_attempt.clone()); let updated_by = updated_payment_attempt.updated_by.to_owned(); let updated_payment_attempt_with_id = payment_attempt .clone() .update_with_attempt_id(&conn, payment_attempt_internal.clone()); Box::pin(self.update_resource( key_manager_state, merchant_key_store, storage_scheme, updated_payment_attempt_with_id, updated_payment_attempt, UpdateResourceParams { updateable: kv::Updateable::PaymentAttemptUpdate(Box::new( kv::PaymentAttemptUpdateMems { orig: payment_attempt, update_data: payment_attempt_internal, }, )), operation: Op::Update(key.clone(), &field, Some(updated_by.as_str())), }, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &ConnectorTransactionId, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( connector_transaction_id, payment_id, merchant_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { // We assume that PaymentAttempt <=> PaymentIntent is a one-to-one relation for now let lookup_id = format!( "pa_conn_trans_{}_{}", merchant_id.get_string_repr(), connector_transaction_id.get_id() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( connector_transaction_id, payment_id, merchant_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key)).await?.try_into_hget() }, || async {self.router_store.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(connector_transaction_id, payment_id, merchant_id, storage_scheme).await}, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let database_call = || { self.router_store .find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let pattern = "pa_*"; let redis_fut = async { let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>( self, KvOperation::<DieselPaymentAttempt>::Scan(pattern), key, )) .await? .try_into_scan(); kv_result.and_then(|mut payment_attempts| { payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at)); payment_attempts .iter() .find(|&pa| pa.status == api_models::enums::AttemptStatus::Charged) .cloned() .ok_or(error_stack::report!( redis_interface::errors::RedisError::NotFound )) }) }; Box::pin(try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let database_call = || { self.router_store .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let pattern = "pa_*"; let redis_fut = async { let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>( self, KvOperation::<DieselPaymentAttempt>::Scan(pattern), key, )) .await? .try_into_scan(); kv_result.and_then(|mut payment_attempts| { payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at)); payment_attempts .iter() .find(|&pa| { pa.status == api_models::enums::AttemptStatus::Charged || pa.status == api_models::enums::AttemptStatus::PartialCharged }) .cloned() .ok_or(error_stack::report!( redis_interface::errors::RedisError::NotFound )) }) }; Box::pin(try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, payment_id: &common_utils::id_type::GlobalPaymentId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let database_call = || { self.router_store .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( key_manager_state, merchant_key_store, payment_id, storage_scheme, ) }; let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match decided_storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalPaymentId { id: payment_id }; let redis_fut = async { let kv_result = kv_wrapper::<DieselPaymentAttempt, _, _>( self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key.clone(), ) .await? .try_into_scan(); let payment_attempt = kv_result.and_then(|mut payment_attempts| { payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at)); payment_attempts .iter() .find(|&pa| { pa.status == diesel_models::enums::AttemptStatus::Charged || pa.status == diesel_models::enums::AttemptStatus::PartialCharged }) .cloned() .ok_or(error_stack::report!( redis_interface::errors::RedisError::NotFound )) })?; let merchant_id = payment_attempt.merchant_id.clone(); PaymentAttempt::convert_back( key_manager_state, payment_attempt, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(redis_interface::errors::RedisError::UnknownResult) }; Box::pin(try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( key_manager_state, merchant_key_store, storage_scheme, DieselPaymentAttempt::find_by_profile_id_connector_transaction_id( &conn, profile_id, connector_transaction_id, ), FindResourceBy::LookupId(label::get_profile_id_connector_transaction_label( profile_id.get_string_repr(), connector_transaction_id, )), ) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, connector_txn_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!( "pa_conn_trans_{}_{connector_txn_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, connector_txn_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, connector_txn_id, storage_scheme, ) .await }, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_id, merchant_id, attempt_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let field = format!("pa_{attempt_id}"); Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&field), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_id, merchant_id, attempt_id, storage_scheme, ) .await }, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_attempt_by_attempt_id_merchant_id( attempt_id, merchant_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!("pa_{}_{attempt_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payment_attempt_by_attempt_id_merchant_id( attempt_id, merchant_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payment_attempt_by_attempt_id_merchant_id( attempt_id, merchant_id, storage_scheme, ) .await }, )) .await } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, attempt_id: &common_utils::id_type::GlobalAttemptId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; self.find_resource_by_id( key_manager_state, merchant_key_store, storage_scheme, DieselPaymentAttempt::find_by_id(&conn, attempt_id), FindResourceBy::LookupId(label::get_global_id_label(attempt_id)), ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_attempts_by_payment_intent_id( &self, key_manager_state: &KeyManagerState, payment_id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> { let conn = pg_connection_read(self).await?; self.filter_resources( key_manager_state, merchant_key_store, storage_scheme, DieselPaymentAttempt::find_by_payment_id(&conn, payment_id), |_| true, FilterResourceParams { key: PartitionKey::GlobalPaymentId { id: payment_id }, pattern: "pa_*", limit: None, }, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_attempt_by_preprocessing_id_merchant_id( preprocessing_id, merchant_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!( "pa_preprocessing_{}_{preprocessing_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payment_attempt_by_preprocessing_id_merchant_id( preprocessing_id, merchant_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payment_attempt_by_preprocessing_id_merchant_id( preprocessing_id, merchant_id, storage_scheme, ) .await }, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_attempts_by_merchant_id_payment_id( merchant_id, payment_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key, )) .await? .try_into_scan() }, || async { self.router_store .find_attempts_by_merchant_id_payment_id( merchant_id, payment_id, storage_scheme, ) .await }, )) .await } } } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filters_for_payments( &self, pi: &[PaymentIntent], merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentListFilters, errors::StorageError> { self.router_store .get_filters_for_payments(pi, merchant_id, storage_scheme) .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method: Option<Vec<common_enums::PaymentMethod>>, payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, card_discovery: Option<Vec<common_enums::CardDiscovery>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method, payment_method_type, authentication_type, merchant_connector_id, card_network, card_discovery, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method_type: Option<Vec<common_enums::PaymentMethod>>, payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.router_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, card_network, storage_scheme, ) .await } } impl DataModelExt for MandateAmountData { type StorageModel = DieselMandateAmountData; fn to_storage_model(self) -> Self::StorageModel { DieselMandateAmountData { amount: self.amount, currency: self.currency, start_date: self.start_date, end_date: self.end_date, metadata: self.metadata, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { amount: storage_model.amount, currency: storage_model.currency, start_date: storage_model.start_date, end_date: storage_model.end_date, metadata: storage_model.metadata, } } } impl DataModelExt for MandateDetails { type StorageModel = DieselMandateDetails; fn to_storage_model(self) -> Self::StorageModel { DieselMandateDetails { update_mandate_id: self.update_mandate_id, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { update_mandate_id: storage_model.update_mandate_id, } } } impl DataModelExt for MandateDataType { type StorageModel = DieselMandateType; fn to_storage_model(self) -> Self::StorageModel { match self { Self::SingleUse(data) => DieselMandateType::SingleUse(data.to_storage_model()), Self::MultiUse(None) => DieselMandateType::MultiUse(None), Self::MultiUse(Some(data)) => { DieselMandateType::MultiUse(Some(data.to_storage_model())) } } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { match storage_model { DieselMandateType::SingleUse(data) => { Self::SingleUse(MandateAmountData::from_storage_model(data)) } DieselMandateType::MultiUse(Some(data)) => { Self::MultiUse(Some(MandateAmountData::from_storage_model(data))) } DieselMandateType::MultiUse(None) => Self::MultiUse(None), } } } #[cfg(feature = "v1")] impl DataModelExt for PaymentAttempt { type StorageModel = DieselPaymentAttempt; fn to_storage_model(self) -> Self::StorageModel { let (connector_transaction_id, processor_transaction_data) = self .connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); DieselPaymentAttempt { payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.net_amount.get_order_amount(), net_amount: Some(self.net_amount.get_total_amount()), currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.net_amount.get_surcharge_amount(), tax_amount: self.net_amount.get_tax_on_surcharge(), payment_method_id: self.payment_method_id, payment_method: self.payment_method, connector_transaction_id, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, error_code: self.error_code, payment_token: self.payment_token, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, card_network: self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_method_data: self.payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details.map(|d| d.to_storage_model()), error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, amount_capturable: self.amount_capturable, updated_by: self.updated_by, authentication_data: self.authentication_data, encoded_data: self.encoded_data, merchant_connector_id: self.merchant_connector_id, unified_code: self.unified_code, unified_message: self.unified_message, external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data.map(|d| d.to_storage_model()), payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, charge_id: self.charge_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, organization_id: self.organization_id, profile_id: self.profile_id, shipping_cost: self.net_amount.get_shipping_cost(), order_tax_amount: self.net_amount.get_order_tax_amount(), connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, issuer_error_code: self.issuer_error_code, issuer_error_message: self.issuer_error_message, setup_future_usage_applied: self.setup_future_usage_applied, routing_approach: self.routing_approach, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|created_by| created_by.to_string()), connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, is_overcapture_enabled: self.is_overcapture_enabled, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { let connector_transaction_id = storage_model .get_optional_connector_transaction_id() .cloned(); Self { net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new( storage_model.amount, storage_model.shipping_cost, storage_model.order_tax_amount, storage_model.surcharge_amount, storage_model.tax_amount, ), payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, currency: storage_model.currency, save_to_locker: storage_model.save_to_locker, connector: storage_model.connector, error_message: storage_model.error_message, offer_amount: storage_model.offer_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, connector_transaction_id, capture_method: storage_model.capture_method, capture_on: storage_model.capture_on, confirm: storage_model.confirm, authentication_type: storage_model.authentication_type, created_at: storage_model.created_at, modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, amount_to_capture: storage_model.amount_to_capture, mandate_id: storage_model.mandate_id, browser_info: storage_model.browser_info, error_code: storage_model.error_code, payment_token: storage_model.payment_token, connector_metadata: storage_model.connector_metadata, payment_experience: storage_model.payment_experience, payment_method_type: storage_model.payment_method_type, payment_method_data: storage_model.payment_method_data, business_sub_label: storage_model.business_sub_label, straight_through_algorithm: storage_model.straight_through_algorithm, preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details .map(MandateDataType::from_storage_model), error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, merchant_connector_id: storage_model.merchant_connector_id, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, external_three_ds_authentication_attempted: storage_model .external_three_ds_authentication_attempted, authentication_connector: storage_model.authentication_connector, authentication_id: storage_model.authentication_id, mandate_data: storage_model .mandate_data .map(MandateDetails::from_storage_model), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, charge_id: storage_model.charge_id, client_source: storage_model.client_source, client_version: storage_model.client_version, customer_acceptance: storage_model.customer_acceptance, organization_id: storage_model.organization_id, profile_id: storage_model.profile_id, connector_mandate_detail: storage_model.connector_mandate_detail, request_extended_authorization: storage_model.request_extended_authorization, extended_authorization_applied: storage_model.extended_authorization_applied, capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, charges: storage_model.charges, issuer_error_code: storage_model.issuer_error_code, issuer_error_message: storage_model.issuer_error_message, processor_merchant_id: storage_model .processor_merchant_id .unwrap_or(storage_model.merchant_id), created_by: storage_model .created_by .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, routing_approach: storage_model.routing_approach, connector_request_reference_id: storage_model.connector_request_reference_id, debit_routing_savings: None, network_transaction_id: storage_model.network_transaction_id, is_overcapture_enabled: storage_model.is_overcapture_enabled, network_details: storage_model.network_details, is_stored_credential: storage_model.is_stored_credential, authorized_amount: storage_model.authorized_amount, } } } #[cfg(feature = "v1")] impl DataModelExt for PaymentAttemptNew { type StorageModel = DieselPaymentAttemptNew; fn to_storage_model(self) -> Self::StorageModel { DieselPaymentAttemptNew { net_amount: Some(self.net_amount.get_total_amount()), payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.net_amount.get_order_amount(), currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.net_amount.get_surcharge_amount(), tax_amount: self.net_amount.get_tax_on_surcharge(), payment_method_id: self.payment_method_id, payment_method: self.payment_method, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at.unwrap_or_else(common_utils::date_time::now), modified_at: self .modified_at .unwrap_or_else(common_utils::date_time::now), last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, error_code: self.error_code, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, card_network: self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|value| value.as_object()) .and_then(|map| map.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_method_data: self.payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details.map(|d| d.to_storage_model()), error_reason: self.error_reason, connector_response_reference_id: self.connector_response_reference_id, multiple_capture_count: self.multiple_capture_count, amount_capturable: self.amount_capturable, updated_by: self.updated_by, authentication_data: self.authentication_data, encoded_data: self.encoded_data, merchant_connector_id: self.merchant_connector_id, unified_code: self.unified_code, unified_message: self.unified_message, external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data.map(|d| d.to_storage_model()), payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, organization_id: self.organization_id, profile_id: self.profile_id, shipping_cost: self.net_amount.get_shipping_cost(), order_tax_amount: self.net_amount.get_order_tax_amount(), connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|created_by| created_by.to_string()), setup_future_usage_applied: self.setup_future_usage_applied, routing_approach: self.routing_approach, connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new( storage_model.amount, storage_model.shipping_cost, storage_model.order_tax_amount, storage_model.surcharge_amount, storage_model.tax_amount, ), payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, currency: storage_model.currency, save_to_locker: storage_model.save_to_locker, connector: storage_model.connector, error_message: storage_model.error_message, offer_amount: storage_model.offer_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, capture_method: storage_model.capture_method, capture_on: storage_model.capture_on, confirm: storage_model.confirm, authentication_type: storage_model.authentication_type, created_at: Some(storage_model.created_at), modified_at: Some(storage_model.modified_at), last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, amount_to_capture: storage_model.amount_to_capture, mandate_id: storage_model.mandate_id, browser_info: storage_model.browser_info, payment_token: storage_model.payment_token, error_code: storage_model.error_code, connector_metadata: storage_model.connector_metadata, payment_experience: storage_model.payment_experience, payment_method_type: storage_model.payment_method_type, payment_method_data: storage_model.payment_method_data, business_sub_label: storage_model.business_sub_label, straight_through_algorithm: storage_model.straight_through_algorithm, preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details .map(MandateDataType::from_storage_model), error_reason: storage_model.error_reason, connector_response_reference_id: storage_model.connector_response_reference_id, multiple_capture_count: storage_model.multiple_capture_count, amount_capturable: storage_model.amount_capturable, updated_by: storage_model.updated_by, authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, merchant_connector_id: storage_model.merchant_connector_id, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, external_three_ds_authentication_attempted: storage_model .external_three_ds_authentication_attempted, authentication_connector: storage_model.authentication_connector, authentication_id: storage_model.authentication_id, mandate_data: storage_model .mandate_data .map(MandateDetails::from_storage_model), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, client_source: storage_model.client_source, client_version: storage_model.client_version, customer_acceptance: storage_model.customer_acceptance, organization_id: storage_model.organization_id, profile_id: storage_model.profile_id, connector_mandate_detail: storage_model.connector_mandate_detail, request_extended_authorization: storage_model.request_extended_authorization, extended_authorization_applied: storage_model.extended_authorization_applied, capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, processor_merchant_id: storage_model .processor_merchant_id .unwrap_or(storage_model.merchant_id), created_by: storage_model .created_by .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, routing_approach: storage_model.routing_approach, connector_request_reference_id: storage_model.connector_request_reference_id, network_transaction_id: storage_model.network_transaction_id, network_details: storage_model.network_details, is_stored_credential: storage_model.is_stored_credential, authorized_amount: storage_model.authorized_amount, } } } #[inline] #[instrument(skip_all)] async fn add_connector_txn_id_to_reverse_lookup<T: DatabaseStore>( store: &KVRouterStore<T>, key: &str, merchant_id: &common_utils::id_type::MerchantId, updated_attempt_attempt_id: &str, connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let field = format!("pa_{updated_attempt_attempt_id}"); let reverse_lookup_new = ReverseLookupNew { lookup_id: format!( "pa_conn_trans_{}_{}", merchant_id.get_string_repr(), connector_transaction_id ), pk_id: key.to_owned(), sk_id: field.clone(), source: "payment_attempt".to_string(), updated_by: storage_scheme.to_string(), }; store .insert_reverse_lookup(reverse_lookup_new, storage_scheme) .await } #[inline] #[instrument(skip_all)] async fn add_preprocessing_id_to_reverse_lookup<T: DatabaseStore>( store: &KVRouterStore<T>, key: &str, merchant_id: &common_utils::id_type::MerchantId, updated_attempt_attempt_id: &str, preprocessing_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let field = format!("pa_{updated_attempt_attempt_id}"); let reverse_lookup_new = ReverseLookupNew { lookup_id: format!( "pa_preprocessing_{}_{}", merchant_id.get_string_repr(), preprocessing_id ), pk_id: key.to_owned(), sk_id: field.clone(), source: "payment_attempt".to_string(), updated_by: storage_scheme.to_string(), }; store .insert_reverse_lookup(reverse_lookup_new, storage_scheme) .await } #[cfg(feature = "v2")] mod label { pub(super) const MODEL_NAME: &str = "payment_attempt_v2"; pub(super) const CLUSTER_LABEL: &str = "pa"; pub(super) fn get_profile_id_connector_transaction_label( profile_id: &str, connector_transaction_id: &str, ) -> String { format!("profile_{profile_id}_conn_txn_{connector_transaction_id}") } pub(super) fn get_global_id_label( attempt_id: &common_utils::id_type::GlobalAttemptId, ) -> String { format!("attempt_global_id_{}", attempt_id.get_string_repr()) } }
crates/storage_impl/src/payments/payment_attempt.rs
storage_impl::src::payments::payment_attempt
17,332
true
// File: crates/storage_impl/src/payments/payment_intent.rs // Module: storage_impl::src::payments::payment_intent #[cfg(feature = "olap")] use api_models::payments::{AmountFilter, Order, SortBy, SortOn}; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; #[cfg(feature = "v2")] use common_utils::fallback_reverse_lookup_not_found; use common_utils::{ ext_traits::{AsyncExt, Encode}, types::keymanager::KeyManagerState, }; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; #[cfg(feature = "v1")] use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate; #[cfg(feature = "v2")] use diesel_models::payment_intent::PaymentIntentUpdateInternal; #[cfg(feature = "olap")] use diesel_models::query::generics::db_metrics; #[cfg(feature = "v2")] use diesel_models::reverse_lookup::ReverseLookupNew; #[cfg(all(feature = "v1", feature = "olap"))] use diesel_models::schema::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, }; #[cfg(all(feature = "v2", feature = "olap"))] use diesel_models::schema_v2::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, }; use diesel_models::{ enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent, }; use error_stack::ResultExt; #[cfg(feature = "olap")] use hyperswitch_domain_models::payments::{ payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, }; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{ payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, PaymentIntent, }, }; use redis_interface::HsetnxReply; #[cfg(feature = "olap")] use router_env::logger; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use crate::connection; use crate::{ diesel_error_to_data_error, errors::{RedisErrorExt, StorageError}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DatabaseStore, }; #[cfg(feature = "v2")] use crate::{errors, lookup::ReverseLookupInterface}; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { type Error = StorageError; #[cfg(feature = "v1")] async fn insert_payment_intent( &self, state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let merchant_id = payment_intent.merchant_id.clone(); let payment_id = payment_intent.get_id().to_owned(); let field = payment_intent.get_id().get_hash_key_for_kv_store(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_intent( state, payment_intent, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let new_payment_intent = payment_intent .clone() .construct_new() .await .change_context(StorageError::EncryptionError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentIntent(Box::new( new_payment_intent, ))), }, }; let diesel_payment_intent = payment_intent .clone() .convert() .await .change_context(StorageError::EncryptionError)?; match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HSetNx( &field, &diesel_payment_intent, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payment_intent", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(payment_intent), Err(error) => Err(error.change_context(StorageError::KVError)), } } } } #[cfg(feature = "v2")] async fn insert_payment_intent( &self, state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_intent( state, payment_intent, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let id = payment_intent.id.clone(); let key = PartitionKey::GlobalPaymentId { id: &id }; let field = format!("pi_{}", id.get_string_repr()); let key_str = key.to_string(); let new_payment_intent = payment_intent .clone() .construct_new() .await .change_context(StorageError::EncryptionError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentIntent(Box::new( new_payment_intent, ))), }, }; let diesel_payment_intent = payment_intent .clone() .convert() .await .change_context(StorageError::EncryptionError)?; if let Some(merchant_reference_id) = &payment_intent.merchant_reference_id { let reverse_lookup = ReverseLookupNew { lookup_id: format!( "pi_merchant_reference_{}_{}", payment_intent.profile_id.get_string_repr(), merchant_reference_id.get_string_repr() ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payment_intent".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; } match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HSetNx( &field, &diesel_payment_intent, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payment_intent", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(payment_intent), Err(error) => Err(error.change_context(StorageError::KVError)), } } } } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let merchant_id = this.merchant_id.clone(); let payment_id = this.get_id().to_owned(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("pi_{}", this.get_id().get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( state, this, payment_intent_update, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_intent_update = DieselPaymentIntentUpdate::from(payment_intent_update); let origin_diesel_intent = this .convert() .await .change_context(StorageError::EncryptionError)?; let diesel_intent = diesel_intent_update .clone() .apply_changeset(origin_diesel_intent.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_intent .encode_to_string_of_json() .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new( kv::PaymentIntentUpdateMems { orig: origin_diesel_intent, update_data: diesel_intent_update, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(StorageError::KVError)?; let payment_intent = PaymentIntent::convert_back( state, diesel_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(payment_intent) } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent_update: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_intent( state, this, payment_intent_update, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let id = this.id.clone(); let merchant_id = this.merchant_id.clone(); let key = PartitionKey::GlobalPaymentId { id: &id }; let field = format!("pi_{}", id.get_string_repr()); let key_str = key.to_string(); let diesel_intent_update = PaymentIntentUpdateInternal::try_from(payment_intent_update) .change_context(StorageError::DeserializationFailed)?; let origin_diesel_intent = this .convert() .await .change_context(StorageError::EncryptionError)?; let diesel_intent = diesel_intent_update .clone() .apply_changeset(origin_diesel_intent.clone()); let redis_value = diesel_intent .encode_to_string_of_json() .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new( kv::PaymentIntentUpdateMems { orig: origin_diesel_intent, update_data: diesel_intent_update, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(StorageError::KVError)?; let payment_intent = PaymentIntent::convert_back( state, diesel_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(payment_intent) } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let database_call = || async { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Find, )) .await; let diesel_payment_intent = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let field = payment_id.get_hash_key_for_kv_store(); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( self, storage_scheme, Op::Find, )) .await; let database_call = || async { let conn: bb8::PooledConnection< '_, async_bb8_diesel::ConnectionManager<diesel::PgConnection>, > = pg_connection_read(self).await?; DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let diesel_payment_intent = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalPaymentId { id }; let field = format!("pi_{}", id.get_string_repr()); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intent_by_constraints( state, merchant_id, filters, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { self.router_store .filter_payment_intents_by_time_range_constraints( state, merchant_id, time_range, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { self.router_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { self.router_store .get_filtered_payment_intents_attempt( state, merchant_id, filters, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, StorageError> { self.router_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, StorageError> { self.router_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, merchant_key_store: &MerchantKeyStore, storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_intent_by_merchant_reference_id_profile_id( state, merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!( "pi_merchant_reference_{}_{}", profile_id.get_string_repr(), merchant_reference_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, *storage_scheme) .await, self.router_store .find_payment_intent_by_merchant_reference_id_profile_id( state, merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; let database_call = || async { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_merchant_reference_id_profile_id( &conn, merchant_reference_id, profile_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let diesel_payment_intent = Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.into(), ) .await .change_context(StorageError::DecryptionError) } } } } #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_payment_intent( &self, state: &KeyManagerState, payment_intent: PaymentIntent, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent = payment_intent .construct_new() .await .change_context(StorageError::EncryptionError)? .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent_update = DieselPaymentIntentUpdate::from(payment_intent); let diesel_payment_intent = this .convert() .await .change_context(StorageError::EncryptionError)? .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent_update = PaymentIntentUpdateInternal::try_from(payment_intent) .change_context(StorageError::DeserializationFailed)?; let diesel_payment_intent = this .convert() .await .change_context(StorageError::EncryptionError)? .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_and_then(|diesel_payment_intent| async { PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, merchant_key_store: &MerchantKeyStore, _storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; let diesel_payment_intent = DieselPaymentIntent::find_by_merchant_reference_id_profile_id( &conn, merchant_reference_id, profile_id, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { use futures::{future::try_join_all, FutureExt}; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); //[#350]: Replace this with Boxable Expression and pass it into generic filter // when https://github.com/rust-lang/rust/issues/52662 becomes stable let mut query = <DieselPaymentIntent as HasTable>::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .order(pi_dsl::created_at.desc()) .into_boxed(); match filters { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())); } PaymentIntentFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( state, starting_after_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( state, ending_before_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; if let Some(currency) = &params.currency { query = query.filter(pi_dsl::currency.eq_any(currency.clone())); } if let Some(status) = &params.status { query = query.filter(pi_dsl::status.eq_any(status.clone())); } } } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<DieselPaymentIntent>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map(|payment_intents| { try_join_all(payment_intents.into_iter().map(|diesel_payment_intent| { PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) })? .await } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { // TODO: Remove this redundant function let payment_filters = (*time_range).into(); self.filter_payment_intent_by_constraints( state, merchant_id, &payment_filters, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = <DieselPaymentIntent as HasTable>::table() .group_by(pi_dsl::status) .select((pi_dsl::status, diesel::dsl::count_star())) .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); if let Some(profile_id) = profile_id_list { query = query.filter(pi_dsl::profile_id.eq_any(profile_id)); } query = query.filter(pi_dsl::created_at.ge(time_range.start_time)); query = match time_range.end_time { Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)), None => query, }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<(common_enums::IntentStatus, i64)>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) .into() }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { use futures::{future::try_join_all, FutureExt}; use crate::DataModelExt; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .inner_join( payment_attempt_schema::table.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)), ) .filter(pa_dsl::merchant_id.eq(merchant_id.to_owned())) // Ensure merchant_ids match, as different merchants can share payment/attempt IDs. .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())) } PaymentIntentFetchConstraints::List(params) => { query = match params.order { Order { on: SortOn::Amount, by: SortBy::Asc, } => query.order(pi_dsl::amount.asc()), Order { on: SortOn::Amount, by: SortBy::Desc, } => query.order(pi_dsl::amount.desc()), Order { on: SortOn::Created, by: SortBy::Asc, } => query.order(pi_dsl::created_at.asc()), Order { on: SortOn::Created, by: SortBy::Desc, } => query.order(pi_dsl::created_at.desc()), }; if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( state, starting_after_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( state, ending_before_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; let connectors = params .connector .as_ref() .map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>()); query = match connectors { Some(connectors) => query.filter(pa_dsl::connector.eq_any(connectors)), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; query = match &params.payment_method { Some(payment_method) => { query.filter(pa_dsl::payment_method.eq_any(payment_method.clone())) } None => query, }; query = match &params.payment_method_type { Some(payment_method_type) => query .filter(pa_dsl::payment_method_type.eq_any(payment_method_type.clone())), None => query, }; query = match &params.authentication_type { Some(authentication_type) => query .filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())), None => query, }; query = match &params.merchant_connector_id { Some(merchant_connector_id) => query.filter( pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()), ), None => query, }; if let Some(card_network) = &params.card_network { query = query.filter(pa_dsl::card_network.eq_any(card_network.clone())); } if let Some(card_discovery) = &params.card_discovery { query = query.filter(pa_dsl::card_discovery.eq_any(card_discovery.clone())); } query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async::<( DieselPaymentIntent, diesel_models::payment_attempt::PaymentAttempt, )>(conn) .await .map(|results| { try_join_all(results.into_iter().map(|(pi, pa)| { PaymentIntent::convert_back( state, pi, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .map(|payment_intent| { payment_intent.map(|payment_intent| { (payment_intent, PaymentAttempt::from_storage_model(pa)) }) }) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) })? .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> { use diesel::NullableExpressionMethods as _; use futures::{future::try_join_all, FutureExt}; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .left_join( payment_attempt_schema::table .on(pi_dsl::active_attempt_id.eq(pa_dsl::id.nullable())), ) // Filtering on merchant_id for payment_attempt is not required for v2 as payment_attempt_ids are globally unique .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::List(params) => { query = match params.order { Order { on: SortOn::Amount, by: SortBy::Asc, } => query.order(pi_dsl::amount.asc()), Order { on: SortOn::Amount, by: SortBy::Desc, } => query.order(pi_dsl::amount.desc()), Order { on: SortOn::Created, by: SortBy::Asc, } => query.order(pi_dsl::created_at.asc()), Order { on: SortOn::Created, by: SortBy::Desc, } => query.order(pi_dsl::created_at.desc()), }; if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_id( state, starting_after_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_id( state, ending_before_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.connector { Some(connector) => query.filter(pa_dsl::connector.eq_any(connector.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; query = match &params.payment_method_type { Some(payment_method_type) => query .filter(pa_dsl::payment_method_type_v2.eq_any(payment_method_type.clone())), None => query, }; query = match &params.payment_method_subtype { Some(payment_method_subtype) => query.filter( pa_dsl::payment_method_subtype.eq_any(payment_method_subtype.clone()), ), None => query, }; query = match &params.authentication_type { Some(authentication_type) => query .filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())), None => query, }; query = match &params.merchant_connector_id { Some(merchant_connector_id) => query.filter( pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()), ), None => query, }; if let Some(card_network) = &params.card_network { query = query.filter(pa_dsl::card_network.eq_any(card_network.clone())); } if let Some(payment_id) = &params.payment_id { query = query.filter(pi_dsl::id.eq(payment_id.clone())); } query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async::<( DieselPaymentIntent, Option<diesel_models::payment_attempt::PaymentAttempt>, )>(conn) .await .change_context(StorageError::DecryptionError) .async_and_then(|output| async { try_join_all(output.into_iter().map( |(pi, pa): (_, Option<diesel_models::payment_attempt::PaymentAttempt>)| async { let payment_intent = PaymentIntent::convert_back( state, pi, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ); let payment_attempt = pa .async_map(|val| { PaymentAttempt::convert_back( state, val, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) }) .map(|val| val.transpose()); let output = futures::try_join!(payment_intent, payment_attempt); output.change_context(StorageError::DecryptionError) }, )) .await }) .await .change_context(StorageError::DecryptionError) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .select(pi_dsl::active_attempt_id) .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .order(pi_dsl::created_at.desc()) .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::List(params) => { if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq(profile_id.clone())); } query = match params.starting_at { Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)), None => query, }; query = match params.ending_at { Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)), None => query, }; query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; if let Some(payment_id) = &params.payment_id { query = query.filter(pi_dsl::id.eq(payment_id.clone())); } query } }; db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<Option<String>>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) .into() }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .select(pi_dsl::active_attempt_id) .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .order(pi_dsl::created_at.desc()) .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())) } PaymentIntentFetchConstraints::List(params) => { if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match params.starting_at { Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)), None => query, }; query = match params.ending_at { Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)), None => query, }; query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; query } }; db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<String>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) .into() }) } }
crates/storage_impl/src/payments/payment_intent.rs
storage_impl::src::payments::payment_intent
12,629
true
// File: crates/storage_impl/src/redis/cache.rs // Module: storage_impl::src::redis::cache use std::{ any::Any, borrow::Cow, fmt::Debug, sync::{Arc, LazyLock}, }; use common_utils::{ errors::{self, CustomResult}, ext_traits::ByteSliceExt, }; use dyn_clone::DynClone; use error_stack::{Report, ResultExt}; use moka::future::Cache as MokaCache; use redis_interface::{errors::RedisError, RedisConnectionPool, RedisValue}; use router_env::{ logger, tracing::{self, instrument}, }; use crate::{ errors::StorageError, metrics, redis::{PubSubInterface, RedisConnInterface}, }; /// Redis channel name used for publishing invalidation messages pub const IMC_INVALIDATION_CHANNEL: &str = "hyperswitch_invalidate"; /// Time to live 30 mins const CACHE_TTL: u64 = 30 * 60; /// Time to idle 10 mins const CACHE_TTI: u64 = 10 * 60; /// Max Capacity of Cache in MB const MAX_CAPACITY: u64 = 30; /// Config Cache with time_to_live as 30 mins and time_to_idle as 10 mins. pub static CONFIG_CACHE: LazyLock<Cache> = LazyLock::new(|| Cache::new("CONFIG_CACHE", CACHE_TTL, CACHE_TTI, None)); /// Accounts cache with time_to_live as 30 mins and size limit pub static ACCOUNTS_CACHE: LazyLock<Cache> = LazyLock::new(|| Cache::new("ACCOUNTS_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); /// Routing Cache pub static ROUTING_CACHE: LazyLock<Cache> = LazyLock::new(|| Cache::new("ROUTING_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); /// 3DS Decision Manager Cache pub static DECISION_MANAGER_CACHE: LazyLock<Cache> = LazyLock::new(|| { Cache::new( "DECISION_MANAGER_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY), ) }); /// Surcharge Cache pub static SURCHARGE_CACHE: LazyLock<Cache> = LazyLock::new(|| Cache::new("SURCHARGE_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); /// CGraph Cache pub static CGRAPH_CACHE: LazyLock<Cache> = LazyLock::new(|| Cache::new("CGRAPH_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); /// PM Filter CGraph Cache pub static PM_FILTERS_CGRAPH_CACHE: LazyLock<Cache> = LazyLock::new(|| { Cache::new( "PM_FILTERS_CGRAPH_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY), ) }); /// Success based Dynamic Algorithm Cache pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| { Cache::new( "SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY), ) }); /// Elimination based Dynamic Algorithm Cache pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| { Cache::new( "ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY), ) }); /// Contract Routing based Dynamic Algorithm Cache pub static CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| { Cache::new( "CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY), ) }); /// Trait which defines the behaviour of types that's gonna be stored in Cache pub trait Cacheable: Any + Send + Sync + DynClone { fn as_any(&self) -> &dyn Any; } #[derive(serde::Serialize, serde::Deserialize)] pub struct CacheRedact<'a> { pub tenant: String, pub kind: CacheKind<'a>, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum CacheKind<'a> { Config(Cow<'a, str>), Accounts(Cow<'a, str>), Routing(Cow<'a, str>), DecisionManager(Cow<'a, str>), Surcharge(Cow<'a, str>), CGraph(Cow<'a, str>), SuccessBasedDynamicRoutingCache(Cow<'a, str>), EliminationBasedDynamicRoutingCache(Cow<'a, str>), ContractBasedDynamicRoutingCache(Cow<'a, str>), PmFiltersCGraph(Cow<'a, str>), All(Cow<'a, str>), } impl CacheKind<'_> { pub(crate) fn get_key_without_prefix(&self) -> &str { match self { CacheKind::Config(key) | CacheKind::Accounts(key) | CacheKind::Routing(key) | CacheKind::DecisionManager(key) | CacheKind::Surcharge(key) | CacheKind::CGraph(key) | CacheKind::SuccessBasedDynamicRoutingCache(key) | CacheKind::EliminationBasedDynamicRoutingCache(key) | CacheKind::ContractBasedDynamicRoutingCache(key) | CacheKind::PmFiltersCGraph(key) | CacheKind::All(key) => key, } } } impl<'a> TryFrom<CacheRedact<'a>> for RedisValue { type Error = Report<errors::ValidationError>; fn try_from(v: CacheRedact<'a>) -> Result<Self, Self::Error> { Ok(Self::from_bytes(serde_json::to_vec(&v).change_context( errors::ValidationError::InvalidValue { message: "Invalid publish key provided in pubsub".into(), }, )?)) } } impl TryFrom<RedisValue> for CacheRedact<'_> { type Error = Report<errors::ValidationError>; fn try_from(v: RedisValue) -> Result<Self, Self::Error> { let bytes = v.as_bytes().ok_or(errors::ValidationError::InvalidValue { message: "InvalidValue received in pubsub".to_string(), })?; bytes .parse_struct("CacheRedact") .change_context(errors::ValidationError::InvalidValue { message: "Unable to deserialize the value from pubsub".to_string(), }) } } impl<T> Cacheable for T where T: Any + Clone + Send + Sync, { fn as_any(&self) -> &dyn Any { self } } dyn_clone::clone_trait_object!(Cacheable); pub struct Cache { name: &'static str, inner: MokaCache<String, Arc<dyn Cacheable>>, } #[derive(Debug, Clone)] pub struct CacheKey { pub key: String, // #TODO: make it usage specific enum Eg: CacheKind { Tenant(String), NoTenant, Partition(String) } pub prefix: String, } impl From<CacheKey> for String { fn from(val: CacheKey) -> Self { if val.prefix.is_empty() { val.key } else { format!("{}:{}", val.prefix, val.key) } } } impl Cache { /// With given `time_to_live` and `time_to_idle` creates a moka cache. /// /// `name` : Cache type name to be used as an attribute in metrics /// `time_to_live`: Time in seconds before an object is stored in a caching system before it’s deleted /// `time_to_idle`: Time in seconds before a `get` or `insert` operation an object is stored in a caching system before it's deleted /// `max_capacity`: Max size in MB's that the cache can hold pub fn new( name: &'static str, time_to_live: u64, time_to_idle: u64, max_capacity: Option<u64>, ) -> Self { // Record the metrics of manual invalidation of cache entry by the application let eviction_listener = move |_, _, cause| { metrics::IN_MEMORY_CACHE_EVICTION_COUNT.add( 1, router_env::metric_attributes!( ("cache_type", name.to_owned()), ("removal_cause", format!("{:?}", cause)), ), ); }; let mut cache_builder = MokaCache::builder() .time_to_live(std::time::Duration::from_secs(time_to_live)) .time_to_idle(std::time::Duration::from_secs(time_to_idle)) .eviction_listener(eviction_listener); if let Some(capacity) = max_capacity { cache_builder = cache_builder.max_capacity(capacity * 1024 * 1024); } Self { name, inner: cache_builder.build(), } } pub async fn push<T: Cacheable>(&self, key: CacheKey, val: T) { self.inner.insert(key.into(), Arc::new(val)).await; } pub async fn get_val<T: Clone + Cacheable>(&self, key: CacheKey) -> Option<T> { let val = self.inner.get::<String>(&key.into()).await; // Add cache hit and cache miss metrics if val.is_some() { metrics::IN_MEMORY_CACHE_HIT .add(1, router_env::metric_attributes!(("cache_type", self.name))); } else { metrics::IN_MEMORY_CACHE_MISS .add(1, router_env::metric_attributes!(("cache_type", self.name))); } let val = (*val?).as_any().downcast_ref::<T>().cloned(); val } /// Check if a key exists in cache pub async fn exists(&self, key: CacheKey) -> bool { self.inner.contains_key::<String>(&key.into()) } pub async fn remove(&self, key: CacheKey) { self.inner.invalidate::<String>(&key.into()).await; } /// Performs any pending maintenance operations needed by the cache. async fn run_pending_tasks(&self) { self.inner.run_pending_tasks().await; } /// Returns an approximate number of entries in this cache. fn get_entry_count(&self) -> u64 { self.inner.entry_count() } pub fn name(&self) -> &'static str { self.name } pub async fn record_entry_count_metric(&self) { self.run_pending_tasks().await; metrics::IN_MEMORY_CACHE_ENTRY_COUNT.record( self.get_entry_count(), router_env::metric_attributes!(("cache_type", self.name)), ); } } #[instrument(skip_all)] pub async fn get_or_populate_redis<T, F, Fut>( redis: &Arc<RedisConnectionPool>, key: impl AsRef<str>, fun: F, ) -> CustomResult<T, StorageError> where T: serde::Serialize + serde::de::DeserializeOwned + Debug, F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send, { let type_name = std::any::type_name::<T>(); let key = key.as_ref(); let redis_val = redis .get_and_deserialize_key::<T>(&key.into(), type_name) .await; let get_data_set_redis = || async { let data = fun().await?; redis .serialize_and_set_key(&key.into(), &data) .await .change_context(StorageError::KVError)?; Ok::<_, Report<StorageError>>(data) }; match redis_val { Err(err) => match err.current_context() { RedisError::NotFound | RedisError::JsonDeserializationFailed => { get_data_set_redis().await } _ => Err(err .change_context(StorageError::KVError) .attach_printable(format!("Error while fetching cache for {type_name}"))), }, Ok(val) => Ok(val), } } #[instrument(skip_all)] pub async fn get_or_populate_in_memory<T, F, Fut>( store: &(dyn RedisConnInterface + Send + Sync), key: &str, fun: F, cache: &Cache, ) -> CustomResult<T, StorageError> where T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone, F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send, { let redis = &store .get_redis_conn() .change_context(StorageError::RedisError( RedisError::RedisConnectionError.into(), )) .attach_printable("Failed to get redis connection")?; let cache_val = cache .get_val::<T>(CacheKey { key: key.to_string(), prefix: redis.key_prefix.clone(), }) .await; if let Some(val) = cache_val { Ok(val) } else { let val = get_or_populate_redis(redis, key, fun).await?; cache .push( CacheKey { key: key.to_string(), prefix: redis.key_prefix.clone(), }, val.clone(), ) .await; Ok(val) } } #[instrument(skip_all)] pub async fn redact_from_redis_and_publish< 'a, K: IntoIterator<Item = CacheKind<'a>> + Send + Clone, >( store: &(dyn RedisConnInterface + Send + Sync), keys: K, ) -> CustomResult<usize, StorageError> { let redis_conn = store .get_redis_conn() .change_context(StorageError::RedisError( RedisError::RedisConnectionError.into(), )) .attach_printable("Failed to get redis connection")?; let redis_keys_to_be_deleted = keys .clone() .into_iter() .map(|val| val.get_key_without_prefix().to_owned().into()) .collect::<Vec<_>>(); let del_replies = redis_conn .delete_multiple_keys(&redis_keys_to_be_deleted) .await .map_err(StorageError::RedisError)?; let deletion_result = redis_keys_to_be_deleted .into_iter() .zip(del_replies) .collect::<Vec<_>>(); logger::debug!(redis_deletion_result=?deletion_result); let futures = keys.into_iter().map(|key| async { redis_conn .clone() .publish(IMC_INVALIDATION_CHANNEL, key) .await .change_context(StorageError::KVError) }); Ok(futures::future::try_join_all(futures) .await? .iter() .sum::<usize>()) } #[instrument(skip_all)] pub async fn publish_and_redact<'a, T, F, Fut>( store: &(dyn RedisConnInterface + Send + Sync), key: CacheKind<'a>, fun: F, ) -> CustomResult<T, StorageError> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send, { let data = fun().await?; redact_from_redis_and_publish(store, [key]).await?; Ok(data) } #[instrument(skip_all)] pub async fn publish_and_redact_multiple<'a, T, F, Fut, K>( store: &(dyn RedisConnInterface + Send + Sync), keys: K, fun: F, ) -> CustomResult<T, StorageError> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send, K: IntoIterator<Item = CacheKind<'a>> + Send + Clone, { let data = fun().await?; redact_from_redis_and_publish(store, keys).await?; Ok(data) } #[cfg(test)] mod cache_tests { use super::*; #[tokio::test] async fn construct_and_get_cache() { let cache = Cache::new("test", 1800, 1800, None); cache .push( CacheKey { key: "key".to_string(), prefix: "prefix".to_string(), }, "val".to_string(), ) .await; assert_eq!( cache .get_val::<String>(CacheKey { key: "key".to_string(), prefix: "prefix".to_string() }) .await, Some(String::from("val")) ); } #[tokio::test] async fn eviction_on_size_test() { let cache = Cache::new("test", 2, 2, Some(0)); cache .push( CacheKey { key: "key".to_string(), prefix: "prefix".to_string(), }, "val".to_string(), ) .await; assert_eq!( cache .get_val::<String>(CacheKey { key: "key".to_string(), prefix: "prefix".to_string() }) .await, None ); } #[tokio::test] async fn invalidate_cache_for_key() { let cache = Cache::new("test", 1800, 1800, None); cache .push( CacheKey { key: "key".to_string(), prefix: "prefix".to_string(), }, "val".to_string(), ) .await; cache .remove(CacheKey { key: "key".to_string(), prefix: "prefix".to_string(), }) .await; assert_eq!( cache .get_val::<String>(CacheKey { key: "key".to_string(), prefix: "prefix".to_string() }) .await, None ); } #[tokio::test] async fn eviction_on_time_test() { let cache = Cache::new("test", 2, 2, None); cache .push( CacheKey { key: "key".to_string(), prefix: "prefix".to_string(), }, "val".to_string(), ) .await; tokio::time::sleep(std::time::Duration::from_secs(3)).await; assert_eq!( cache .get_val::<String>(CacheKey { key: "key".to_string(), prefix: "prefix".to_string() }) .await, None ); } }
crates/storage_impl/src/redis/cache.rs
storage_impl::src::redis::cache
4,041
true
// File: crates/storage_impl/src/redis/kv_store.rs // Module: storage_impl::src::redis::kv_store use std::{fmt::Debug, sync::Arc}; use common_utils::errors::CustomResult; use diesel_models::enums::MerchantStorageScheme; use error_stack::report; use redis_interface::errors::RedisError; use router_derive::TryGetEnumVariant; use router_env::logger; use serde::de; use crate::{kv_router_store::KVRouterStore, metrics, store::kv::TypedSql, UniqueConstraints}; pub trait KvStorePartition { fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 { crc32fast::hash(key.to_string().as_bytes()) % u32::from(num_partitions) } fn shard_key(key: PartitionKey<'_>, num_partitions: u8) -> String { format!("shard_{}", Self::partition_number(key, num_partitions)) } } #[allow(unused)] #[derive(Clone)] pub enum PartitionKey<'a> { MerchantIdPaymentId { merchant_id: &'a common_utils::id_type::MerchantId, payment_id: &'a common_utils::id_type::PaymentId, }, CombinationKey { combination: &'a str, }, MerchantIdCustomerId { merchant_id: &'a common_utils::id_type::MerchantId, customer_id: &'a common_utils::id_type::CustomerId, }, #[cfg(feature = "v2")] MerchantIdMerchantReferenceId { merchant_id: &'a common_utils::id_type::MerchantId, merchant_reference_id: &'a str, }, MerchantIdPayoutId { merchant_id: &'a common_utils::id_type::MerchantId, payout_id: &'a common_utils::id_type::PayoutId, }, MerchantIdPayoutAttemptId { merchant_id: &'a common_utils::id_type::MerchantId, payout_attempt_id: &'a str, }, MerchantIdMandateId { merchant_id: &'a common_utils::id_type::MerchantId, mandate_id: &'a str, }, #[cfg(feature = "v2")] GlobalId { id: &'a str, }, #[cfg(feature = "v2")] GlobalPaymentId { id: &'a common_utils::id_type::GlobalPaymentId, }, } // PartitionKey::MerchantIdPaymentId {merchant_id, payment_id} impl std::fmt::Display for PartitionKey<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, } => f.write_str(&format!( "mid_{}_pid_{}", merchant_id.get_string_repr(), payment_id.get_string_repr() )), PartitionKey::CombinationKey { combination } => f.write_str(combination), PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, } => f.write_str(&format!( "mid_{}_cust_{}", merchant_id.get_string_repr(), customer_id.get_string_repr() )), #[cfg(feature = "v2")] PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id, } => f.write_str(&format!( "mid_{}_cust_{merchant_reference_id}", merchant_id.get_string_repr() )), PartitionKey::MerchantIdPayoutId { merchant_id, payout_id, } => f.write_str(&format!( "mid_{}_po_{}", merchant_id.get_string_repr(), payout_id.get_string_repr() )), PartitionKey::MerchantIdPayoutAttemptId { merchant_id, payout_attempt_id, } => f.write_str(&format!( "mid_{}_poa_{payout_attempt_id}", merchant_id.get_string_repr() )), PartitionKey::MerchantIdMandateId { merchant_id, mandate_id, } => f.write_str(&format!( "mid_{}_mandate_{mandate_id}", merchant_id.get_string_repr() )), #[cfg(feature = "v2")] PartitionKey::GlobalId { id } => f.write_str(&format!("global_cust_{id}")), #[cfg(feature = "v2")] PartitionKey::GlobalPaymentId { id } => { f.write_str(&format!("global_payment_{}", id.get_string_repr())) } } } } pub trait RedisConnInterface { fn get_redis_conn( &self, ) -> error_stack::Result<Arc<redis_interface::RedisConnectionPool>, RedisError>; } /// An enum to represent what operation to do on pub enum KvOperation<'a, S: serde::Serialize + Debug> { Hset((&'a str, String), TypedSql), SetNx(&'a S, TypedSql), HSetNx(&'a str, &'a S, TypedSql), HGet(&'a str), Get, Scan(&'a str), } #[derive(TryGetEnumVariant)] #[error(RedisError::UnknownResult)] pub enum KvResult<T: de::DeserializeOwned> { HGet(T), Get(T), Hset(()), SetNx(redis_interface::SetnxReply), HSetNx(redis_interface::HsetnxReply), Scan(Vec<T>), } impl<T> std::fmt::Display for KvOperation<'_, T> where T: serde::Serialize + Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { KvOperation::Hset(_, _) => f.write_str("Hset"), KvOperation::SetNx(_, _) => f.write_str("Setnx"), KvOperation::HSetNx(_, _, _) => f.write_str("HSetNx"), KvOperation::HGet(_) => f.write_str("Hget"), KvOperation::Get => f.write_str("Get"), KvOperation::Scan(_) => f.write_str("Scan"), } } } pub async fn kv_wrapper<'a, T, D, S>( store: &KVRouterStore<D>, op: KvOperation<'a, S>, partition_key: PartitionKey<'a>, ) -> CustomResult<KvResult<T>, RedisError> where T: de::DeserializeOwned, D: crate::database::store::DatabaseStore, S: serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync, { let redis_conn = store.get_redis_conn()?; let key = format!("{partition_key}"); let type_name = std::any::type_name::<T>(); let operation = op.to_string(); let ttl = store.ttl_for_kv; let result = async { match op { KvOperation::Hset(value, sql) => { logger::debug!(kv_operation= %operation, value = ?value); redis_conn .set_hash_fields(&key.into(), value, Some(ttl.into())) .await?; store .push_to_drainer_stream::<S>(sql, partition_key) .await?; Ok(KvResult::Hset(())) } KvOperation::HGet(field) => { let result = redis_conn .get_hash_field_and_deserialize(&key.into(), field, type_name) .await?; Ok(KvResult::HGet(result)) } KvOperation::Scan(pattern) => { let result: Vec<T> = redis_conn .hscan_and_deserialize(&key.into(), pattern, None) .await .and_then(|result| { if result.is_empty() { Err(report!(RedisError::NotFound)) } else { Ok(result) } })?; Ok(KvResult::Scan(result)) } KvOperation::HSetNx(field, value, sql) => { logger::debug!(kv_operation= %operation, value = ?value); value.check_for_constraints(&redis_conn).await?; let result = redis_conn .serialize_and_set_hash_field_if_not_exist(&key.into(), field, value, Some(ttl)) .await?; if matches!(result, redis_interface::HsetnxReply::KeySet) { store .push_to_drainer_stream::<S>(sql, partition_key) .await?; Ok(KvResult::HSetNx(result)) } else { Err(report!(RedisError::SetNxFailed)) } } KvOperation::SetNx(value, sql) => { logger::debug!(kv_operation= %operation, value = ?value); let result = redis_conn .serialize_and_set_key_if_not_exist(&key.into(), value, Some(ttl.into())) .await?; value.check_for_constraints(&redis_conn).await?; if matches!(result, redis_interface::SetnxReply::KeySet) { store .push_to_drainer_stream::<S>(sql, partition_key) .await?; Ok(KvResult::SetNx(result)) } else { Err(report!(RedisError::SetNxFailed)) } } KvOperation::Get => { let result = redis_conn .get_and_deserialize_key(&key.into(), type_name) .await?; Ok(KvResult::Get(result)) } } }; let attributes = router_env::metric_attributes!(("operation", operation.clone())); result .await .inspect(|_| { logger::debug!(kv_operation= %operation, status="success"); metrics::KV_OPERATION_SUCCESSFUL.add(1, attributes); }) .inspect_err(|err| { logger::error!(kv_operation = %operation, status="error", error = ?err); metrics::KV_OPERATION_FAILED.add(1, attributes); }) } pub enum Op<'a> { Insert, Update(PartitionKey<'a>, &'a str, Option<&'a str>), Find, } impl std::fmt::Display for Op<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Op::Insert => f.write_str("insert"), Op::Find => f.write_str("find"), Op::Update(p_key, _, updated_by) => { f.write_str(&format!("update_{p_key} for updated_by_{updated_by:?}")) } } } } pub async fn decide_storage_scheme<T, D>( store: &KVRouterStore<T>, storage_scheme: MerchantStorageScheme, operation: Op<'_>, ) -> MerchantStorageScheme where D: de::DeserializeOwned + serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync, T: crate::database::store::DatabaseStore, { if store.soft_kill_mode { let ops = operation.to_string(); let updated_scheme = match operation { Op::Insert => MerchantStorageScheme::PostgresOnly, Op::Find => MerchantStorageScheme::RedisKv, Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly, Op::Update(partition_key, field, Some(_updated_by)) => { match Box::pin(kv_wrapper::<D, _, _>( store, KvOperation::<D>::HGet(field), partition_key, )) .await { Ok(_) => { metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(1, &[]); MerchantStorageScheme::RedisKv } Err(_) => MerchantStorageScheme::PostgresOnly, } } Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly, }; let type_name = std::any::type_name::<D>(); logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme,entity = %type_name, operation = %ops); updated_scheme } else { storage_scheme } }
crates/storage_impl/src/redis/kv_store.rs
storage_impl::src::redis::kv_store
2,618
true
// File: crates/storage_impl/src/redis/pub_sub.rs // Module: storage_impl::src::redis::pub_sub use std::sync::atomic; use error_stack::ResultExt; use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; use router_env::{logger, tracing::Instrument}; use crate::redis::cache::{ CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, DECISION_MANAGER_CACHE, ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE, }; #[async_trait::async_trait] pub trait PubSubInterface { async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError>; async fn publish<'a>( &self, channel: &str, key: CacheKind<'a>, ) -> error_stack::Result<usize, redis_errors::RedisError>; async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError>; } #[async_trait::async_trait] impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { #[inline] async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> { // Spawns a task that will automatically re-subscribe to any channels or channel patterns used by the client. self.subscriber.manage_subscriptions(); self.subscriber .subscribe::<(), &str>(channel) .await .change_context(redis_errors::RedisError::SubscribeError)?; // Spawn only one thread handling all the published messages to different channels if self .subscriber .is_subscriber_handler_spawned .compare_exchange( false, true, atomic::Ordering::SeqCst, atomic::Ordering::SeqCst, ) .is_ok() { let redis_clone = self.clone(); let _task_handle = tokio::spawn( async move { if let Err(pubsub_error) = redis_clone.on_message().await { logger::error!(?pubsub_error); } } .in_current_span(), ); } Ok(()) } #[inline] async fn publish<'a>( &self, channel: &str, key: CacheKind<'a>, ) -> error_stack::Result<usize, redis_errors::RedisError> { let key = CacheRedact { kind: key, tenant: self.key_prefix.clone(), }; self.publisher .publish( channel, RedisValue::try_from(key).change_context(redis_errors::RedisError::PublishError)?, ) .await .change_context(redis_errors::RedisError::SubscribeError) } #[inline] async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> { logger::debug!("Started on message"); let mut rx = self.subscriber.on_message(); while let Ok(message) = rx.recv().await { let channel_name = message.channel.to_string(); logger::debug!("Received message on channel: {channel_name}"); match channel_name.as_str() { super::cache::IMC_INVALIDATION_CHANNEL => { let message = match CacheRedact::try_from(RedisValue::new(message.value)) .change_context(redis_errors::RedisError::OnMessageError) { Ok(value) => value, Err(err) => { logger::error!(value_conversion_err=?err); continue; } }; let key = match message.kind { CacheKind::Config(key) => { CONFIG_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Accounts(key) => { ACCOUNTS_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::CGraph(key) => { CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::PmFiltersCGraph(key) => { PM_FILTERS_CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::EliminationBasedDynamicRoutingCache(key) => { ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::ContractBasedDynamicRoutingCache(key) => { CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::SuccessBasedDynamicRoutingCache(key) => { SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Routing(key) => { ROUTING_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::DecisionManager(key) => { DECISION_MANAGER_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Surcharge(key) => { SURCHARGE_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::All(key) => { CONFIG_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ACCOUNTS_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; PM_FILTERS_CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ROUTING_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; DECISION_MANAGER_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; SURCHARGE_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } }; logger::debug!( key_prefix=?message.tenant.clone(), channel_name=?channel_name, "Done invalidating {key}" ); } _ => { logger::debug!("Received message from unknown channel: {channel_name}"); } } } Ok(()) } }
crates/storage_impl/src/redis/pub_sub.rs
storage_impl::src::redis::pub_sub
1,736
true
// File: crates/storage_impl/src/mock_db/payment_attempt.rs // Module: storage_impl::src::mock_db::payment_attempt use common_utils::errors::CustomResult; #[cfg(feature = "v2")] use common_utils::{id_type, types::keymanager::KeyManagerState}; use diesel_models::enums as storage_enums; #[cfg(feature = "v2")] use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; #[cfg(feature = "v1")] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; use hyperswitch_domain_models::payments::payment_attempt::{ PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate, }; use super::MockDb; use crate::errors::StorageError; #[cfg(feature = "v1")] use crate::DataModelExt; #[async_trait::async_trait] impl PaymentAttemptInterface for MockDb { type Error = StorageError; #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, _payment_id: &common_utils::id_type::PaymentId, _merchant_id: &common_utils::id_type::MerchantId, _attempt_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filters_for_payments( &self, _pi: &[hyperswitch_domain_models::payments::PaymentIntent], _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters, StorageError, > { Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_total_count_of_filtered_payment_attempts( &self, _merchant_id: &common_utils::id_type::MerchantId, _active_attempt_ids: &[String], _connector: Option<Vec<api_models::enums::Connector>>, _payment_method: Option<Vec<common_enums::PaymentMethod>>, _payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, _authentication_type: Option<Vec<common_enums::AuthenticationType>>, _merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, _card_network: Option<Vec<storage_enums::CardNetwork>>, _card_discovery: Option<Vec<storage_enums::CardDiscovery>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { Err(StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_total_count_of_filtered_payment_attempts( &self, _merchant_id: &id_type::MerchantId, _active_attempt_ids: &[String], _connector: Option<Vec<api_models::enums::Connector>>, _payment_method_type: Option<Vec<common_enums::PaymentMethod>>, _payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>, _authentication_type: Option<Vec<common_enums::AuthenticationType>>, _merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, _card_network: Option<Vec<storage_enums::CardNetwork>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, _attempt_id: &str, _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v2")] async fn find_payment_attempt_by_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, _attempt_id: &id_type::GlobalAttemptId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v2")] async fn find_payment_attempts_by_payment_intent_id( &self, _key_manager_state: &KeyManagerState, _id: &id_type::GlobalPaymentId, _merchant_key_store: &MerchantKeyStore, _storage_scheme: common_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, _preprocessing_id: &str, _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _connector_txn_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, _profile_id: &id_type::ProfileId, _connector_transaction_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payment_id: &common_utils::id_type::PaymentId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] #[allow(clippy::panic)] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttemptNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { let mut payment_attempts = self.payment_attempts.lock().await; let time = common_utils::date_time::now(); let payment_attempt = PaymentAttempt { payment_id: payment_attempt.payment_id, merchant_id: payment_attempt.merchant_id, attempt_id: payment_attempt.attempt_id, status: payment_attempt.status, net_amount: payment_attempt.net_amount, currency: payment_attempt.currency, save_to_locker: payment_attempt.save_to_locker, connector: payment_attempt.connector, error_message: payment_attempt.error_message, offer_amount: payment_attempt.offer_amount, payment_method_id: payment_attempt.payment_method_id, payment_method: payment_attempt.payment_method, connector_transaction_id: None, capture_method: payment_attempt.capture_method, capture_on: payment_attempt.capture_on, confirm: payment_attempt.confirm, authentication_type: payment_attempt.authentication_type, created_at: payment_attempt.created_at.unwrap_or(time), modified_at: payment_attempt.modified_at.unwrap_or(time), last_synced: payment_attempt.last_synced, cancellation_reason: payment_attempt.cancellation_reason, amount_to_capture: payment_attempt.amount_to_capture, mandate_id: None, browser_info: None, payment_token: None, error_code: payment_attempt.error_code, connector_metadata: None, charge_id: None, payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, payment_method_data: payment_attempt.payment_method_data, business_sub_label: payment_attempt.business_sub_label, straight_through_algorithm: payment_attempt.straight_through_algorithm, mandate_details: payment_attempt.mandate_details, preprocessing_step_id: payment_attempt.preprocessing_step_id, error_reason: payment_attempt.error_reason, multiple_capture_count: payment_attempt.multiple_capture_count, connector_response_reference_id: None, amount_capturable: payment_attempt.amount_capturable, updated_by: storage_scheme.to_string(), authentication_data: payment_attempt.authentication_data, encoded_data: payment_attempt.encoded_data, merchant_connector_id: payment_attempt.merchant_connector_id, unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, external_three_ds_authentication_attempted: payment_attempt .external_three_ds_authentication_attempted, authentication_connector: payment_attempt.authentication_connector, authentication_id: payment_attempt.authentication_id, mandate_data: payment_attempt.mandate_data, payment_method_billing_address_id: payment_attempt.payment_method_billing_address_id, fingerprint_id: payment_attempt.fingerprint_id, client_source: payment_attempt.client_source, client_version: payment_attempt.client_version, customer_acceptance: payment_attempt.customer_acceptance, organization_id: payment_attempt.organization_id, profile_id: payment_attempt.profile_id, connector_mandate_detail: payment_attempt.connector_mandate_detail, request_extended_authorization: payment_attempt.request_extended_authorization, extended_authorization_applied: payment_attempt.extended_authorization_applied, capture_before: payment_attempt.capture_before, card_discovery: payment_attempt.card_discovery, charges: None, issuer_error_code: None, issuer_error_message: None, processor_merchant_id: payment_attempt.processor_merchant_id, created_by: payment_attempt.created_by, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, routing_approach: payment_attempt.routing_approach, connector_request_reference_id: payment_attempt.connector_request_reference_id, debit_routing_savings: None, network_transaction_id: payment_attempt.network_transaction_id, is_overcapture_enabled: None, network_details: payment_attempt.network_details, is_stored_credential: payment_attempt.is_stored_credential, authorized_amount: payment_attempt.authorized_amount, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) } #[cfg(feature = "v2")] #[allow(clippy::panic)] async fn insert_payment_attempt( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, _payment_attempt: PaymentAttempt, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { let mut payment_attempts = self.payment_attempts.lock().await; let item = payment_attempts .iter_mut() .find(|item| item.attempt_id == this.attempt_id) .unwrap(); *item = PaymentAttempt::from_storage_model( payment_attempt .to_storage_model() .apply_changeset(this.to_storage_model()), ); Ok(item.clone()) } #[cfg(feature = "v2")] async fn update_payment_attempt( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, _this: PaymentAttempt, _payment_attempt: PaymentAttemptUpdate, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, _connector_transaction_id: &common_utils::types::ConnectorTransactionId, _payment_id: &common_utils::id_type::PaymentId, _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { let payment_attempts = self.payment_attempts.lock().await; Ok(payment_attempts .iter() .find(|payment_attempt| { payment_attempt.payment_id == *payment_id && payment_attempt.merchant_id.eq(merchant_id) }) .cloned() .unwrap()) } #[cfg(feature = "v1")] #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { let payment_attempts = self.payment_attempts.lock().await; Ok(payment_attempts .iter() .find(|payment_attempt| { payment_attempt.payment_id == *payment_id && payment_attempt.merchant_id.eq(merchant_id) && (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged || payment_attempt.status == storage_enums::AttemptStatus::Charged) }) .cloned() .unwrap()) } #[cfg(feature = "v2")] #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, payment_id: &id_type::GlobalPaymentId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { let payment_attempts = self.payment_attempts.lock().await; Ok(payment_attempts .iter() .find(|payment_attempt| { payment_attempt.payment_id == *payment_id && (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged || payment_attempt.status == storage_enums::AttemptStatus::Charged) }) .cloned() .unwrap()) } }
crates/storage_impl/src/mock_db/payment_attempt.rs
storage_impl::src::mock_db::payment_attempt
3,493
true
// File: crates/storage_impl/src/mock_db/payouts.rs // Module: storage_impl::src::mock_db::payouts use common_utils::errors::CustomResult; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttempt, payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate}, }; use crate::{errors::StorageError, MockDb}; #[async_trait::async_trait] impl PayoutsInterface for MockDb { type Error = StorageError; async fn find_payout_by_merchant_id_payout_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payout_id: &common_utils::id_type::PayoutId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Payouts, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn update_payout( &self, _this: &Payouts, _payout_update: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Payouts, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn insert_payout( &self, _payout: PayoutsNew, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Payouts, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn find_optional_payout_by_merchant_id_payout_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payout_id: &common_utils::id_type::PayoutId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<Payouts>, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "olap")] async fn filter_payouts_by_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, _filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<Payouts>, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "olap")] async fn filter_payouts_and_attempts( &self, _merchant_id: &common_utils::id_type::MerchantId, _filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult< Vec<( Payouts, PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )>, StorageError, > { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "olap")] async fn filter_payouts_by_time_range_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, _time_range: &common_utils::types::TimeRange, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<Payouts>, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "olap")] async fn get_total_count_of_filtered_payouts( &self, _merchant_id: &common_utils::id_type::MerchantId, _active_payout_ids: &[common_utils::id_type::PayoutId], _connector: Option<Vec<api_models::enums::PayoutConnectors>>, _currency: Option<Vec<storage_enums::Currency>>, _status: Option<Vec<storage_enums::PayoutStatus>>, _payout_method: Option<Vec<storage_enums::PayoutType>>, ) -> CustomResult<i64, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, ) -> CustomResult<Vec<common_utils::id_type::PayoutId>, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } }
crates/storage_impl/src/mock_db/payouts.rs
storage_impl::src::mock_db::payouts
1,096
true
// File: crates/storage_impl/src/mock_db/redis_conn.rs // Module: storage_impl::src::mock_db::redis_conn use std::sync::Arc; use redis_interface::errors::RedisError; use super::MockDb; use crate::redis::kv_store::RedisConnInterface; impl RedisConnInterface for MockDb { fn get_redis_conn( &self, ) -> Result<Arc<redis_interface::RedisConnectionPool>, error_stack::Report<RedisError>> { self.redis.get_redis_conn() } }
crates/storage_impl/src/mock_db/redis_conn.rs
storage_impl::src::mock_db::redis_conn
113
true
// File: crates/storage_impl/src/mock_db/payout_attempt.rs // Module: storage_impl::src::mock_db::payout_attempt use common_utils::errors::CustomResult; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payouts::{ payout_attempt::{ PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate, }, payouts::Payouts, }; use super::MockDb; use crate::errors::StorageError; #[async_trait::async_trait] impl PayoutAttemptInterface for MockDb { type Error = StorageError; async fn update_payout_attempt( &self, _this: &PayoutAttempt, _payout_attempt_update: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn insert_payout_attempt( &self, _payout_attempt: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payout_attempt_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _connector_payout_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? } async fn get_filters_for_payouts( &self, _payouts: &[Payouts], _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters, StorageError, > { Err(StorageError::MockDbError)? } async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _merchant_order_reference_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { Err(StorageError::MockDbError)? } }
crates/storage_impl/src/mock_db/payout_attempt.rs
storage_impl::src::mock_db::payout_attempt
675
true
// File: crates/storage_impl/src/mock_db/payment_intent.rs // Module: storage_impl::src::mock_db::payment_intent use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models::enums as storage_enums; #[cfg(feature = "v1")] use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::behaviour::Conversion; use hyperswitch_domain_models::{ merchant_key_store::MerchantKeyStore, payments::{ payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, PaymentIntent, }, }; use super::MockDb; use crate::errors::StorageError; #[async_trait::async_trait] impl PaymentIntentInterface for MockDb { type Error = StorageError; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _merchant_key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result< Vec<( PaymentIntent, Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, )>, StorageError, > { Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _time_range: &common_utils::types::TimeRange, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<String>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<Option<String>>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result< Vec<( PaymentIntent, hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, )>, StorageError, > { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } #[allow(clippy::panic)] async fn insert_payment_intent( &self, _state: &KeyManagerState, new: PaymentIntent, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let mut payment_intents = self.payment_intents.lock().await; payment_intents.push(new.clone()); Ok(new) } #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, update: PaymentIntentUpdate, key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let mut payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter_mut() .find(|item| item.get_id() == this.get_id() && item.merchant_id == this.merchant_id) .unwrap(); let diesel_payment_intent_update = diesel_models::PaymentIntentUpdate::from(update); let diesel_payment_intent = payment_intent .clone() .convert() .await .change_context(StorageError::EncryptionError)?; *payment_intent = PaymentIntent::convert_back( state, diesel_payment_intent_update.apply_changeset(diesel_payment_intent), key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError)?; Ok(payment_intent.clone()) } #[cfg(feature = "v2")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn update_payment_intent( &self, _state: &KeyManagerState, _this: PaymentIntent, _update: PaymentIntentUpdate, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { todo!() } #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn find_payment_intent_by_payment_id_merchant_id( &self, _state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; Ok(payment_intents .iter() .find(|payment_intent| { payment_intent.get_id() == payment_id && payment_intent.merchant_id.eq(merchant_id) }) .cloned() .unwrap()) } #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, _state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, _merchant_key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter() .find(|payment_intent| payment_intent.get_id() == id) .ok_or(StorageError::ValueNotFound( "PaymentIntent not found".to_string(), ))?; Ok(payment_intent.clone()) } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, _state: &KeyManagerState, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, _merchant_key_store: &MerchantKeyStore, _storage_scheme: &common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter() .find(|payment_intent| { payment_intent.merchant_reference_id.as_ref() == Some(merchant_reference_id) && payment_intent.profile_id.eq(profile_id) }) .ok_or(StorageError::ValueNotFound( "PaymentIntent not found".to_string(), ))?; Ok(payment_intent.clone()) } }
crates/storage_impl/src/mock_db/payment_intent.rs
storage_impl::src::mock_db::payment_intent
2,135
true
// File: crates/storage_impl/src/payouts/payouts.rs // Module: storage_impl::src::payouts::payouts #[cfg(feature = "olap")] use api_models::enums::PayoutConnectors; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use common_utils::ext_traits::Encode; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; #[cfg(all(feature = "v1", feature = "olap"))] use diesel::{JoinOnDsl, NullableExpressionMethods}; #[cfg(feature = "olap")] use diesel_models::{ address::Address as DieselAddress, customers::Customer as DieselCustomer, enums as storage_enums, query::generics::db_metrics, schema::payouts::dsl as po_dsl, }; use diesel_models::{ enums::MerchantStorageScheme, kv, payouts::{ Payouts as DieselPayouts, PayoutsNew as DieselPayoutsNew, PayoutsUpdate as DieselPayoutsUpdate, }, }; #[cfg(all(feature = "olap", feature = "v1"))] use diesel_models::{ payout_attempt::PayoutAttempt as DieselPayoutAttempt, schema::{address::dsl as add_dsl, customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl}, }; use error_stack::ResultExt; #[cfg(feature = "olap")] use hyperswitch_domain_models::payouts::PayoutFetchConstraints; use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttempt, payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate}, }; use redis_interface::HsetnxReply; #[cfg(feature = "olap")] use router_env::logger; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use crate::connection; #[cfg(all(feature = "olap", feature = "v1"))] use crate::store::schema::{ address::all_columns as addr_all_columns, customers::all_columns as cust_all_columns, payout_attempt::all_columns as poa_all_columns, payouts::all_columns as po_all_columns, }; use crate::{ diesel_error_to_data_error, errors::{RedisErrorExt, StorageError}, kv_router_store::KVRouterStore, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DataModelExt, DatabaseStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_payout( &self, new: PayoutsNew, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store.insert_payout(new, storage_scheme).await } MerchantStorageScheme::RedisKv => { let merchant_id = new.merchant_id.clone(); let payout_id = new.payout_id.clone(); let key = PartitionKey::MerchantIdPayoutId { merchant_id: &merchant_id, payout_id: &payout_id, }; let key_str = key.to_string(); let field = format!("po_{}", new.payout_id.get_string_repr()); let created_payout = Payouts { payout_id: new.payout_id.clone(), merchant_id: new.merchant_id.clone(), customer_id: new.customer_id.clone(), address_id: new.address_id.clone(), payout_type: new.payout_type, payout_method_id: new.payout_method_id.clone(), amount: new.amount, destination_currency: new.destination_currency, source_currency: new.source_currency, description: new.description.clone(), recurring: new.recurring, auto_fulfill: new.auto_fulfill, return_url: new.return_url.clone(), entity_type: new.entity_type, metadata: new.metadata.clone(), created_at: new.created_at, last_modified_at: new.last_modified_at, profile_id: new.profile_id.clone(), status: new.status, attempt_count: new.attempt_count, confirm: new.confirm, payout_link_id: new.payout_link_id.clone(), client_secret: new.client_secret.clone(), priority: new.priority, }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Payouts(new.to_storage_model())), }, }; match Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HSetNx( &field, &created_payout.clone().to_storage_model(), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payouts", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_payout), Err(error) => Err(error.change_context(StorageError::KVError)), } } } } #[instrument(skip_all)] async fn update_payout( &self, this: &Payouts, payout_update: PayoutsUpdate, payout_attempt: &PayoutAttempt, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let key = PartitionKey::MerchantIdPayoutId { merchant_id: &this.merchant_id, payout_id: &this.payout_id, }; let field = format!("po_{}", this.payout_id.get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Update(key.clone(), &field, None), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payout(this, payout_update, payout_attempt, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_payout_update = payout_update.to_storage_model(); let origin_diesel_payout = this.clone().to_storage_model(); let diesel_payout = diesel_payout_update .clone() .apply_changeset(origin_diesel_payout.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_payout .encode_to_string_of_json() .change_context(StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems { orig: origin_diesel_payout, update_data: diesel_payout_update, })), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPayouts>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(StorageError::KVError)?; Ok(Payouts::from_storage_model(diesel_payout)) } } } #[instrument(skip_all)] async fn find_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let database_call = || async { let conn = pg_connection_read(self).await?; DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPayoutId { merchant_id, payout_id, }; let field = format!("po_{}", payout_id.get_string_repr()); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } } .map(Payouts::from_storage_model) } #[instrument(skip_all)] async fn find_optional_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Option<Payouts>, StorageError> { let database_call = || async { let conn = pg_connection_read(self).await?; DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { let maybe_payouts = database_call().await?; Ok(maybe_payouts.filter(|payout| &payout.payout_id == payout_id)) } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPayoutId { merchant_id, payout_id, }; let field = format!("po_{}", payout_id.get_string_repr()); Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HGet(&field), key, )) .await? .try_into_hget() .map(Some) }, database_call, )) .await } } .map(|payout| payout.map(Payouts::from_storage_model)) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { self.router_store .filter_payouts_by_constraints(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_and_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>, StorageError, > { self.router_store .filter_payouts_and_attempts(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] #[instrument[skip_all]] async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { self.router_store .filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme) .await } #[cfg(feature = "olap")] async fn get_total_count_of_filtered_payouts( &self, merchant_id: &common_utils::id_type::MerchantId, active_payout_ids: &[common_utils::id_type::PayoutId], connector: Option<Vec<PayoutConnectors>>, currency: Option<Vec<storage_enums::Currency>>, status: Option<Vec<storage_enums::PayoutStatus>>, payout_method: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, StorageError> { self.router_store .get_total_count_of_filtered_payouts( merchant_id, active_payout_ids, connector, currency, status, payout_method, ) .await } #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> { self.router_store .filter_active_payout_ids_by_constraints(merchant_id, constraints) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { type Error = StorageError; #[instrument(skip_all)] async fn insert_payout( &self, new: PayoutsNew, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_write(self).await?; new.to_storage_model() .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(Payouts::from_storage_model) } #[instrument(skip_all)] async fn update_payout( &self, this: &Payouts, payout: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_write(self).await?; this.clone() .to_storage_model() .update(&conn, payout.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(Payouts::from_storage_model) } #[instrument(skip_all)] async fn find_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_read(self).await?; DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map(Payouts::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn find_optional_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Option<Payouts>, StorageError> { let conn = pg_connection_read(self).await?; DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map(|x| x.map(Payouts::from_storage_model)) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); //[#350]: Replace this with Boxable Expression and pass it into generic filter // when https://github.com/rust-lang/rust/issues/52662 becomes stable let mut query = <DieselPayouts as HasTable>::table() .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); match filters { PayoutFetchConstraints::Single { payout_id } => { query = query.filter(po_dsl::payout_id.eq(payout_id.to_owned())); } PayoutFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(po_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(po_dsl::profile_id.eq(profile_id.clone())); } query = match (params.starting_at, params.starting_after_id.as_ref()) { (Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payout_by_merchant_id_payout_id( merchant_id, starting_after_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, params.ending_before_id.as_ref()) { (Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payout_by_merchant_id_payout_id( merchant_id, ending_before_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); if let Some(currency) = &params.currency { query = query.filter(po_dsl::destination_currency.eq_any(currency.clone())); } if let Some(status) = &params.status { query = query.filter(po_dsl::status.eq_any(status.clone())); } } } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>( query.get_results_async::<DieselPayouts>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map(|payouts| { payouts .into_iter() .map(Payouts::from_storage_model) .collect::<Vec<Payouts>>() }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payout records"), ) .into() }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payouts_and_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>, StorageError, > { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPayouts::table() .inner_join( diesel_models::schema::payout_attempt::table .on(poa_dsl::payout_id.eq(po_dsl::payout_id)), ) .left_join( diesel_models::schema::customers::table .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)), ) .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned())) .left_outer_join( diesel_models::schema::address::table .on(add_dsl::address_id.nullable().eq(po_dsl::address_id)), ) .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); query = match filters { PayoutFetchConstraints::Single { payout_id } => { query.filter(po_dsl::payout_id.eq(payout_id.to_owned())) } PayoutFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(po_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(po_dsl::profile_id.eq(profile_id.clone())); } if let Some(merchant_order_reference_id_filter) = &params.merchant_order_reference_id { query = query.filter( poa_dsl::merchant_order_reference_id .eq(merchant_order_reference_id_filter.clone()), ); } query = match (params.starting_at, params.starting_after_id.as_ref()) { (Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { let starting_at = self .find_payout_by_merchant_id_payout_id( merchant_id, starting_after_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, params.ending_before_id.as_ref()) { (Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { let ending_at = self .find_payout_by_merchant_id_payout_id( merchant_id, ending_before_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); if let Some(currency) = &params.currency { query = query.filter(po_dsl::destination_currency.eq_any(currency.clone())); } let connectors = params .connector .as_ref() .map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>()); query = match connectors { Some(conn_filters) if !conn_filters.is_empty() => { query.filter(poa_dsl::connector.eq_any(conn_filters)) } _ => query, }; query = match &params.status { Some(status_filters) if !status_filters.is_empty() => { query.filter(po_dsl::status.eq_any(status_filters.clone())) } _ => query, }; query = match &params.payout_method { Some(payout_method) if !payout_method.is_empty() => { query.filter(po_dsl::payout_type.eq_any(payout_method.clone())) } _ => query, }; query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .select(( po_all_columns, poa_all_columns, cust_all_columns.nullable(), addr_all_columns.nullable(), )) .get_results_async::<( DieselPayouts, DieselPayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>(conn) .await .map(|results| { results .into_iter() .map(|(pi, pa, c, add)| { ( Payouts::from_storage_model(pi), PayoutAttempt::from_storage_model(pa), c, add, ) }) .collect() }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payout records"), ) .into() }) } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] async fn filter_payouts_and_attempts( &self, _merchant_id: &common_utils::id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<DieselCustomer>, Option<DieselAddress>, )>, StorageError, > { todo!() } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { let payout_filters = (*time_range).into(); self.filter_payouts_by_constraints(merchant_id, &payout_filters, storage_scheme) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_total_count_of_filtered_payouts( &self, merchant_id: &common_utils::id_type::MerchantId, active_payout_ids: &[common_utils::id_type::PayoutId], connector: Option<Vec<PayoutConnectors>>, currency: Option<Vec<storage_enums::Currency>>, status: Option<Vec<storage_enums::PayoutStatus>>, payout_type: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, StorageError> { let conn = self .db_store .get_replica_pool() .get() .await .change_context(StorageError::DatabaseConnectionError)?; let connector_strings = connector.as_ref().map(|connectors| { connectors .iter() .map(|c| c.to_string()) .collect::<Vec<String>>() }); DieselPayouts::get_total_count_of_payouts( &conn, merchant_id, active_payout_ids, connector_strings, currency, status, payout_type, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_active_payout_ids_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPayouts::table() .inner_join( diesel_models::schema::payout_attempt::table .on(poa_dsl::payout_id.eq(po_dsl::payout_id)), ) .left_join( diesel_models::schema::customers::table .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)), ) .select(po_dsl::payout_id) .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned())) .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); query = match constraints { PayoutFetchConstraints::Single { payout_id } => { query.filter(po_dsl::payout_id.eq(payout_id.to_owned())) } PayoutFetchConstraints::List(params) => { if let Some(customer_id) = &params.customer_id { query = query.filter(po_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(po_dsl::profile_id.eq(profile_id.clone())); } query = match params.starting_at { Some(starting_at) => query.filter(po_dsl::created_at.ge(starting_at)), None => query, }; query = match params.ending_at { Some(ending_at) => query.filter(po_dsl::created_at.le(ending_at)), None => query, }; query = match &params.currency { Some(currency) => { query.filter(po_dsl::destination_currency.eq_any(currency.clone())) } None => query, }; query = match &params.status { Some(status) => query.filter(po_dsl::status.eq_any(status.clone())), None => query, }; query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>( query.get_results_async::<String>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payout records"), ) })? .into_iter() .map(|s| { common_utils::id_type::PayoutId::try_from(std::borrow::Cow::Owned(s)) .change_context(StorageError::DeserializationFailed) .attach_printable("Failed to deserialize PayoutId from database string") }) .collect::<error_stack::Result<Vec<_>, _>>() } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] async fn filter_active_payout_ids_by_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, _constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> { todo!() } } impl DataModelExt for Payouts { type StorageModel = DieselPayouts; fn to_storage_model(self) -> Self::StorageModel { DieselPayouts { payout_id: self.payout_id, merchant_id: self.merchant_id, customer_id: self.customer_id, address_id: self.address_id, payout_type: self.payout_type, payout_method_id: self.payout_method_id, amount: self.amount, destination_currency: self.destination_currency, source_currency: self.source_currency, description: self.description, recurring: self.recurring, auto_fulfill: self.auto_fulfill, return_url: self.return_url, entity_type: self.entity_type, metadata: self.metadata, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, status: self.status, attempt_count: self.attempt_count, confirm: self.confirm, payout_link_id: self.payout_link_id, client_secret: self.client_secret, priority: self.priority, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_id: storage_model.payout_id, merchant_id: storage_model.merchant_id, customer_id: storage_model.customer_id, address_id: storage_model.address_id, payout_type: storage_model.payout_type, payout_method_id: storage_model.payout_method_id, amount: storage_model.amount, destination_currency: storage_model.destination_currency, source_currency: storage_model.source_currency, description: storage_model.description, recurring: storage_model.recurring, auto_fulfill: storage_model.auto_fulfill, return_url: storage_model.return_url, entity_type: storage_model.entity_type, metadata: storage_model.metadata, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, status: storage_model.status, attempt_count: storage_model.attempt_count, confirm: storage_model.confirm, payout_link_id: storage_model.payout_link_id, client_secret: storage_model.client_secret, priority: storage_model.priority, } } } impl DataModelExt for PayoutsNew { type StorageModel = DieselPayoutsNew; fn to_storage_model(self) -> Self::StorageModel { DieselPayoutsNew { payout_id: self.payout_id, merchant_id: self.merchant_id, customer_id: self.customer_id, address_id: self.address_id, payout_type: self.payout_type, payout_method_id: self.payout_method_id, amount: self.amount, destination_currency: self.destination_currency, source_currency: self.source_currency, description: self.description, recurring: self.recurring, auto_fulfill: self.auto_fulfill, return_url: self.return_url, entity_type: self.entity_type, metadata: self.metadata, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, status: self.status, attempt_count: self.attempt_count, confirm: self.confirm, payout_link_id: self.payout_link_id, client_secret: self.client_secret, priority: self.priority, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_id: storage_model.payout_id, merchant_id: storage_model.merchant_id, customer_id: storage_model.customer_id, address_id: storage_model.address_id, payout_type: storage_model.payout_type, payout_method_id: storage_model.payout_method_id, amount: storage_model.amount, destination_currency: storage_model.destination_currency, source_currency: storage_model.source_currency, description: storage_model.description, recurring: storage_model.recurring, auto_fulfill: storage_model.auto_fulfill, return_url: storage_model.return_url, entity_type: storage_model.entity_type, metadata: storage_model.metadata, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, status: storage_model.status, attempt_count: storage_model.attempt_count, confirm: storage_model.confirm, payout_link_id: storage_model.payout_link_id, client_secret: storage_model.client_secret, priority: storage_model.priority, } } } impl DataModelExt for PayoutsUpdate { type StorageModel = DieselPayoutsUpdate; fn to_storage_model(self) -> Self::StorageModel { match self { Self::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, } => DieselPayoutsUpdate::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, }, Self::PayoutMethodIdUpdate { payout_method_id } => { DieselPayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } } Self::RecurringUpdate { recurring } => { DieselPayoutsUpdate::RecurringUpdate { recurring } } Self::AttemptCountUpdate { attempt_count } => { DieselPayoutsUpdate::AttemptCountUpdate { attempt_count } } Self::StatusUpdate { status } => DieselPayoutsUpdate::StatusUpdate { status }, } } #[allow(clippy::todo)] fn from_storage_model(_storage_model: Self::StorageModel) -> Self { todo!("Reverse map should no longer be needed") } }
crates/storage_impl/src/payouts/payouts.rs
storage_impl::src::payouts::payouts
8,397
true
// File: crates/storage_impl/src/payouts/payout_attempt.rs // Module: storage_impl::src::payouts::payout_attempt use std::str::FromStr; use api_models::enums::PayoutConnectors; use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found}; use diesel_models::{ enums::MerchantStorageScheme, kv, payout_attempt::{ PayoutAttempt as DieselPayoutAttempt, PayoutAttemptNew as DieselPayoutAttemptNew, PayoutAttemptUpdate as DieselPayoutAttemptUpdate, }, reverse_lookup::ReverseLookup, ReverseLookupNew, }; use error_stack::ResultExt; use hyperswitch_domain_models::payouts::{ payout_attempt::{ PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate, PayoutListFilters, }, payouts::Payouts, }; use redis_interface::HsetnxReply; use router_env::{instrument, logger, tracing}; use crate::{ diesel_error_to_data_error, errors, errors::RedisErrorExt, kv_router_store::KVRouterStore, lookup::ReverseLookupInterface, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, DataModelExt, DatabaseStore, }; #[async_trait::async_trait] impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_payout_attempt( &self, new_payout_attempt: PayoutAttemptNew, payouts: &Payouts, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payout_attempt(new_payout_attempt, payouts, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let merchant_id = new_payout_attempt.merchant_id.clone(); let payout_attempt_id = new_payout_attempt.payout_id.clone(); let key = PartitionKey::MerchantIdPayoutAttemptId { merchant_id: &merchant_id, payout_attempt_id: payout_attempt_id.get_string_repr(), }; let key_str = key.to_string(); let created_attempt = PayoutAttempt { payout_attempt_id: new_payout_attempt.payout_attempt_id.clone(), payout_id: new_payout_attempt.payout_id.clone(), additional_payout_method_data: new_payout_attempt .additional_payout_method_data .clone(), customer_id: new_payout_attempt.customer_id.clone(), merchant_id: new_payout_attempt.merchant_id.clone(), address_id: new_payout_attempt.address_id.clone(), connector: new_payout_attempt.connector.clone(), connector_payout_id: new_payout_attempt.connector_payout_id.clone(), payout_token: new_payout_attempt.payout_token.clone(), status: new_payout_attempt.status, is_eligible: new_payout_attempt.is_eligible, error_message: new_payout_attempt.error_message.clone(), error_code: new_payout_attempt.error_code.clone(), business_country: new_payout_attempt.business_country, business_label: new_payout_attempt.business_label.clone(), created_at: new_payout_attempt.created_at, last_modified_at: new_payout_attempt.last_modified_at, profile_id: new_payout_attempt.profile_id.clone(), merchant_connector_id: new_payout_attempt.merchant_connector_id.clone(), routing_info: new_payout_attempt.routing_info.clone(), unified_code: new_payout_attempt.unified_code.clone(), unified_message: new_payout_attempt.unified_message.clone(), merchant_order_reference_id: new_payout_attempt .merchant_order_reference_id .clone(), payout_connector_metadata: new_payout_attempt.payout_connector_metadata.clone(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PayoutAttempt( new_payout_attempt.to_storage_model(), )), }, }; // Reverse lookup for payout_attempt_id let field = format!("poa_{}", created_attempt.payout_attempt_id); let reverse_lookup = ReverseLookupNew { lookup_id: format!( "poa_{}_{}", &created_attempt.merchant_id.get_string_repr(), &created_attempt.payout_attempt_id, ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payout_attempt".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>( self, KvOperation::<DieselPayoutAttempt>::HSetNx( &field, &created_attempt.clone().to_storage_model(), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "payout attempt", key: Some(key_str), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_attempt), Err(error) => Err(error.change_context(errors::StorageError::KVError)), } } } } #[instrument(skip_all)] async fn update_payout_attempt( &self, this: &PayoutAttempt, payout_update: PayoutAttemptUpdate, payouts: &Payouts, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let key = PartitionKey::MerchantIdPayoutAttemptId { merchant_id: &this.merchant_id, payout_attempt_id: this.payout_id.get_string_repr(), }; let field = format!("poa_{}", this.payout_attempt_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Update(key.clone(), &field, None), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payout_attempt(this, payout_update, payouts, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let diesel_payout_update = payout_update.clone().to_storage_model(); let origin_diesel_payout = this.clone().to_storage_model(); let diesel_payout = diesel_payout_update .clone() .apply_changeset(origin_diesel_payout.clone()); // Check for database presence as well Maybe use a read replica here ? let redis_value = diesel_payout .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PayoutAttemptUpdate( kv::PayoutAttemptUpdateMems { orig: origin_diesel_payout, update_data: diesel_payout_update, }, )), }, }; let updated_attempt = PayoutAttempt::from_storage_model( payout_update .to_storage_model() .apply_changeset(this.clone().to_storage_model()), ); let old_connector_payout_id = this.connector_payout_id.clone(); match ( old_connector_payout_id, updated_attempt.connector_payout_id.clone(), ) { (Some(old), Some(new)) if old != new => { add_connector_payout_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.payout_attempt_id.as_str(), new.as_str(), storage_scheme, ) .await?; } (None, Some(new)) => { add_connector_payout_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.payout_attempt_id.as_str(), new.as_str(), storage_scheme, ) .await?; } _ => {} } Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(PayoutAttempt::from_storage_model(diesel_payout)) } } } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!("poa_{}_{payout_attempt_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await }, )) .await } } } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!( "po_conn_payout_{}_{connector_payout_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await }, )) .await } } } #[instrument(skip_all)] async fn get_filters_for_payouts( &self, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutListFilters, errors::StorageError> { self.router_store .get_filters_for_payouts(payouts, merchant_id, storage_scheme) .await } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_order_reference_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { self.router_store .find_payout_attempt_by_merchant_id_merchant_order_reference_id( merchant_id, merchant_order_reference_id, storage_scheme, ) .await } } #[async_trait::async_trait] impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> { type Error = errors::StorageError; #[instrument(skip_all)] async fn insert_payout_attempt( &self, new: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; new.to_storage_model() .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) } #[instrument(skip_all)] async fn update_payout_attempt( &self, this: &PayoutAttempt, payout: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; this.clone() .to_storage_model() .update_with_attempt_id(&conn, payout.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_payout_attempt_id( &conn, merchant_id, payout_attempt_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_payout_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_connector_payout_id( &conn, merchant_id, connector_payout_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } #[instrument(skip_all)] async fn get_filters_for_payouts( &self, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PayoutListFilters, errors::StorageError> { let conn = pg_connection_read(self).await?; let payouts = payouts .iter() .cloned() .map(|payouts| payouts.to_storage_model()) .collect::<Vec<diesel_models::Payouts>>(); DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( |(connector, currency, status, payout_method)| PayoutListFilters { connector: connector .iter() .filter_map(|c| { PayoutConnectors::from_str(c) .map_err(|e| { logger::error!( "Failed to parse payout connector '{}' - {}", c, e ); }) .ok() }) .collect(), currency, status, payout_method, }, ) } #[instrument(skip_all)] async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_order_reference_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_merchant_order_reference_id( &conn, merchant_id, merchant_order_reference_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) } } impl DataModelExt for PayoutAttempt { type StorageModel = DieselPayoutAttempt; fn to_storage_model(self) -> Self::StorageModel { DieselPayoutAttempt { payout_attempt_id: self.payout_attempt_id, payout_id: self.payout_id, customer_id: self.customer_id, merchant_id: self.merchant_id, address_id: self.address_id, connector: self.connector, connector_payout_id: self.connector_payout_id, payout_token: self.payout_token, status: self.status, is_eligible: self.is_eligible, error_message: self.error_message, error_code: self.error_code, business_country: self.business_country, business_label: self.business_label, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, unified_code: self.unified_code, unified_message: self.unified_message, additional_payout_method_data: self.additional_payout_method_data, merchant_order_reference_id: self.merchant_order_reference_id, payout_connector_metadata: self.payout_connector_metadata, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_attempt_id: storage_model.payout_attempt_id, payout_id: storage_model.payout_id, customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, address_id: storage_model.address_id, connector: storage_model.connector, connector_payout_id: storage_model.connector_payout_id, payout_token: storage_model.payout_token, status: storage_model.status, is_eligible: storage_model.is_eligible, error_message: storage_model.error_message, error_code: storage_model.error_code, business_country: storage_model.business_country, business_label: storage_model.business_label, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, additional_payout_method_data: storage_model.additional_payout_method_data, merchant_order_reference_id: storage_model.merchant_order_reference_id, payout_connector_metadata: storage_model.payout_connector_metadata, } } } impl DataModelExt for PayoutAttemptNew { type StorageModel = DieselPayoutAttemptNew; fn to_storage_model(self) -> Self::StorageModel { DieselPayoutAttemptNew { payout_attempt_id: self.payout_attempt_id, payout_id: self.payout_id, customer_id: self.customer_id, merchant_id: self.merchant_id, address_id: self.address_id, connector: self.connector, connector_payout_id: self.connector_payout_id, payout_token: self.payout_token, status: self.status, is_eligible: self.is_eligible, error_message: self.error_message, error_code: self.error_code, business_country: self.business_country, business_label: self.business_label, created_at: self.created_at, last_modified_at: self.last_modified_at, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, unified_code: self.unified_code, unified_message: self.unified_message, additional_payout_method_data: self.additional_payout_method_data, merchant_order_reference_id: self.merchant_order_reference_id, payout_connector_metadata: self.payout_connector_metadata, } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { payout_attempt_id: storage_model.payout_attempt_id, payout_id: storage_model.payout_id, customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, address_id: storage_model.address_id, connector: storage_model.connector, connector_payout_id: storage_model.connector_payout_id, payout_token: storage_model.payout_token, status: storage_model.status, is_eligible: storage_model.is_eligible, error_message: storage_model.error_message, error_code: storage_model.error_code, business_country: storage_model.business_country, business_label: storage_model.business_label, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at, profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, unified_code: storage_model.unified_code, unified_message: storage_model.unified_message, additional_payout_method_data: storage_model.additional_payout_method_data, merchant_order_reference_id: storage_model.merchant_order_reference_id, payout_connector_metadata: storage_model.payout_connector_metadata, } } } impl DataModelExt for PayoutAttemptUpdate { type StorageModel = DieselPayoutAttemptUpdate; fn to_storage_model(self) -> Self::StorageModel { match self { Self::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, } => DieselPayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, }, Self::PayoutTokenUpdate { payout_token } => { DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token } } Self::BusinessUpdate { business_country, business_label, address_id, customer_id, } => DieselPayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, }, Self::UpdateRouting { connector, routing_info, merchant_connector_id, } => DieselPayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, }, Self::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => DieselPayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, }, } } #[allow(clippy::todo)] fn from_storage_model(_storage_model: Self::StorageModel) -> Self { todo!("Reverse map should no longer be needed") } } #[inline] #[instrument(skip_all)] async fn add_connector_payout_id_to_reverse_lookup<T: DatabaseStore>( store: &KVRouterStore<T>, key: &str, merchant_id: &common_utils::id_type::MerchantId, updated_attempt_attempt_id: &str, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let field = format!("poa_{updated_attempt_attempt_id}"); let reverse_lookup_new = ReverseLookupNew { lookup_id: format!( "po_conn_payout_{}_{}", merchant_id.get_string_repr(), connector_payout_id ), pk_id: key.to_owned(), sk_id: field.clone(), source: "payout_attempt".to_string(), updated_by: storage_scheme.to_string(), }; store .insert_reverse_lookup(reverse_lookup_new, storage_scheme) .await }
crates/storage_impl/src/payouts/payout_attempt.rs
storage_impl::src::payouts::payout_attempt
5,680
true
// File: crates/common_utils/src/tokenization.rs // Module: common_utils::src::tokenization //! Module for tokenization-related functionality //! //! This module provides types and functions for handling tokenized payment data, //! including response structures and token generation utilities. use crate::consts::TOKEN_LENGTH; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] /// Generates a new token string /// /// # Returns /// A randomly generated token string of length `TOKEN_LENGTH` pub fn generate_token() -> String { use nanoid::nanoid; nanoid!(TOKEN_LENGTH) }
crates/common_utils/src/tokenization.rs
common_utils::src::tokenization
128
true
// File: crates/common_utils/src/ext_traits.rs // Module: common_utils::src::ext_traits //! This module holds traits for extending functionalities for existing datatypes //! & inbuilt datatypes. use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, Strategy}; use quick_xml::de; #[cfg(all(feature = "logs", feature = "async_ext"))] use router_env::logger; use serde::{Deserialize, Serialize}; use crate::{ crypto, errors::{self, CustomResult}, fp_utils::when, }; /// Encode interface /// An interface for performing type conversions and serialization pub trait Encode<'e> where Self: 'e + std::fmt::Debug, { // If needed get type information/custom error implementation. /// /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically to convert into json, by using `serde_json` fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into JSON `String`. fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize` fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize; } impl<'e, A> Encode<'e> for A where Self: 'e + std::fmt::Debug, { fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_json::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("string")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_urlencoded::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } // Check without two functions can we combine this fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_urlencoded::to_string(self) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_json::to_string(self) .change_context(errors::ParsingError::EncodeError("json")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { quick_xml::se::to_string(self) .change_context(errors::ParsingError::EncodeError("xml")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize, { serde_json::to_value(self) .change_context(errors::ParsingError::EncodeError("json-value")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize, { serde_json::to_vec(self) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } } /// Extending functionalities of `bytes::Bytes` pub trait BytesExt { /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl BytesExt for bytes::Bytes { fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { use bytes::Buf; serde_json::from_slice::<T>(self.chunk()) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let variable_type = std::any::type_name::<T>(); let value = serde_json::from_slice::<serde_json::Value>(self) .unwrap_or_else(|_| serde_json::Value::String(String::new())); format!( "Unable to parse {variable_type} from bytes {:?}", Secret::<_, masking::JsonMaskStrategy>::new(value) ) }) } } /// Extending functionalities of `[u8]` for performing parsing pub trait ByteSliceExt { /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl ByteSliceExt for [u8] { #[track_caller] fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_slice(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let value = serde_json::from_slice::<serde_json::Value>(self) .unwrap_or_else(|_| serde_json::Value::String(String::new())); format!( "Unable to parse {type_name} from &[u8] {:?}", Secret::<_, masking::JsonMaskStrategy>::new(value) ) }) } } /// Extending functionalities of `serde_json::Value` for performing parsing pub trait ValueExt { /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned; } impl ValueExt for serde_json::Value { fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned, { serde_json::from_value::<T>(self.clone()) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { format!( "Unable to parse {type_name} from serde_json::Value: {:?}", // Required to prevent logging sensitive data in case of deserialization failure Secret::<_, masking::JsonMaskStrategy>::new(self) ) }) } } impl<MaskingStrategy> ValueExt for Secret<serde_json::Value, MaskingStrategy> where MaskingStrategy: Strategy<serde_json::Value>, { fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned, { self.expose().parse_value(type_name) } } impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> { fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned, { self.into_inner().parse_value(type_name) } } /// Extending functionalities of `String` for performing parsing pub trait StringExt<T> { /// Convert `String` into type `<T>` (which being an `enum`) fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl<T> StringExt<T> for String { fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static, { T::from_str(&self) .change_context(errors::ParsingError::EnumParseFailure(enum_name)) .attach_printable_lazy(|| format!("Invalid enum variant {self:?} for enum {enum_name}")) } fn parse_struct<'de>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_str::<T>(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { format!( "Unable to parse {type_name} from string {:?}", Secret::<_, masking::JsonMaskStrategy>::new(serde_json::Value::String( self.clone() )) ) }) } } /// Extending functionalities of Wrapper types for idiomatic #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] pub trait AsyncExt<A> { /// Output type of the map function type WrappedSelf<T>; /// Extending map by allowing functions which are async async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send; /// Extending the `and_then` by allowing functions which are async async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send; /// Extending `unwrap_or_else` to allow async fallback async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = A> + Send; /// Extending `or_else` to allow async fallback that returns Self::WrappedSelf<A> async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send; } #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> { type WrappedSelf<T> = Result<T, E>; async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send, { match self { Ok(a) => func(a).await, Err(err) => Err(err), } } async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send, { match self { Ok(a) => Ok(func(a).await), Err(err) => Err(err), } } async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = A> + Send, { match self { Ok(a) => a, Err(_err) => { #[cfg(feature = "logs")] logger::error!("Error: {:?}", _err); func().await } } } async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send, { match self { Ok(a) => Ok(a), Err(_err) => { #[cfg(feature = "logs")] logger::error!("Error: {:?}", _err); func().await } } } } #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] impl<A: Send> AsyncExt<A> for Option<A> { type WrappedSelf<T> = Option<T>; async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send, { match self { Some(a) => func(a).await, None => None, } } async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send, { match self { Some(a) => Some(func(a).await), None => None, } } async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = A> + Send, { match self { Some(a) => a, None => func().await, } } async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A> where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send, { match self { Some(a) => Some(a), None => func().await, } } } /// Extension trait for validating application configuration. This trait provides utilities to /// check whether the value is either the default value or is empty. pub trait ConfigExt { /// Returns whether the value of `self` is the default value for `Self`. fn is_default(&self) -> bool where Self: Default + PartialEq<Self>, { *self == Self::default() } /// Returns whether the value of `self` is empty after trimming whitespace on both left and /// right ends. fn is_empty_after_trim(&self) -> bool; /// Returns whether the value of `self` is the default value for `Self` or empty after trimming /// whitespace on both left and right ends. fn is_default_or_empty(&self) -> bool where Self: Default + PartialEq<Self>, { self.is_default() || self.is_empty_after_trim() } } impl ConfigExt for u32 { fn is_empty_after_trim(&self) -> bool { false } } impl ConfigExt for String { fn is_empty_after_trim(&self) -> bool { self.trim().is_empty() } } impl<T, U> ConfigExt for Secret<T, U> where T: ConfigExt + Default + PartialEq<T>, U: Strategy<T>, { fn is_default(&self) -> bool where T: Default + PartialEq<T>, { *self.peek() == T::default() } fn is_empty_after_trim(&self) -> bool { self.peek().is_empty_after_trim() } fn is_default_or_empty(&self) -> bool where T: Default + PartialEq<T>, { self.peek().is_default() || self.peek().is_empty_after_trim() } } /// Extension trait for deserializing XML strings using `quick-xml` crate pub trait XmlExt { /// Deserialize an XML string into the specified type `<T>`. fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned; } impl XmlExt for &str { fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned, { de::from_str(self) } } /// Extension trait for Option to validate missing fields pub trait OptionExt<T> { /// check if the current option is Some fn check_value_present( &self, field_name: &'static str, ) -> CustomResult<(), errors::ValidationError>; /// Throw missing required field error when the value is None fn get_required_value( self, field_name: &'static str, ) -> CustomResult<T, errors::ValidationError>; /// Try parsing the option as Enum fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; /// Try parsing the option as Type fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned; /// update option value fn update_value(&mut self, value: Option<T>); } impl<T> OptionExt<T> for Option<T> where T: std::fmt::Debug, { #[track_caller] fn check_value_present( &self, field_name: &'static str, ) -> CustomResult<(), errors::ValidationError> { when(self.is_none(), || { Err(errors::ValidationError::MissingRequiredField { field_name: field_name.to_string(), }) .attach_printable(format!("Missing required field {field_name} in {self:?}")) }) } // This will allow the error message that was generated in this function to point to the call site #[track_caller] fn get_required_value( self, field_name: &'static str, ) -> CustomResult<T, errors::ValidationError> { match self { Some(v) => Ok(v), None => Err(errors::ValidationError::MissingRequiredField { field_name: field_name.to_string(), }) .attach_printable(format!("Missing required field {field_name} in {self:?}")), } } #[track_caller] fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static, { let value = self .get_required_value(enum_name) .change_context(errors::ParsingError::UnknownError)?; E::from_str(value.as_ref()) .change_context(errors::ParsingError::UnknownError) .attach_printable_lazy(|| format!("Invalid {{ {enum_name}: {value:?} }} ")) } #[track_caller] fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned, { let value = self .get_required_value(type_name) .change_context(errors::ParsingError::UnknownError)?; value.parse_value(type_name) } fn update_value(&mut self, value: Self) { if let Some(a) = value { *self = Some(a) } } }
crates/common_utils/src/ext_traits.rs
common_utils::src::ext_traits
5,173
true
// File: crates/common_utils/src/request.rs // Module: common_utils::src::request use masking::{Maskable, Secret}; use reqwest::multipart::Form; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; pub type Headers = std::collections::HashSet<(String, Maskable<String>)>; #[derive( Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "UPPERCASE")] #[strum(serialize_all = "UPPERCASE")] pub enum Method { Get, Post, Put, Delete, Patch, } #[derive(Deserialize, Serialize, Debug)] pub enum ContentType { Json, FormUrlEncoded, FormData, Xml, } fn default_request_headers() -> [(String, Maskable<String>); 1] { use http::header; [(header::VIA.to_string(), "HyperSwitch".to_string().into())] } #[derive(Debug)] pub struct Request { pub url: String, pub headers: Headers, pub method: Method, pub certificate: Option<Secret<String>>, pub certificate_key: Option<Secret<String>>, pub body: Option<RequestContent>, pub ca_certificate: Option<Secret<String>>, } impl std::fmt::Debug for RequestContent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::Json(_) => "JsonRequestBody", Self::FormUrlEncoded(_) => "FormUrlEncodedRequestBody", Self::FormData(_) => "FormDataRequestBody", Self::Xml(_) => "XmlRequestBody", Self::RawBytes(_) => "RawBytesRequestBody", }) } } pub enum RequestContent { Json(Box<dyn masking::ErasedMaskSerialize + Send>), FormUrlEncoded(Box<dyn masking::ErasedMaskSerialize + Send>), FormData((Form, Box<dyn masking::ErasedMaskSerialize + Send>)), Xml(Box<dyn masking::ErasedMaskSerialize + Send>), RawBytes(Vec<u8>), } impl RequestContent { pub fn get_inner_value(&self) -> Secret<String> { match self { Self::Json(i) => serde_json::to_string(&i).unwrap_or_default().into(), Self::FormUrlEncoded(i) => serde_urlencoded::to_string(i).unwrap_or_default().into(), Self::Xml(i) => quick_xml::se::to_string(&i).unwrap_or_default().into(), Self::FormData((_, i)) => serde_json::to_string(i).unwrap_or_default().into(), Self::RawBytes(_) => String::new().into(), } } } impl Request { pub fn new(method: Method, url: &str) -> Self { Self { method, url: String::from(url), headers: std::collections::HashSet::new(), certificate: None, certificate_key: None, body: None, ca_certificate: None, } } pub fn set_body<T: Into<RequestContent>>(&mut self, body: T) { self.body.replace(body.into()); } pub fn add_default_headers(&mut self) { self.headers.extend(default_request_headers()); } pub fn add_header(&mut self, header: &str, value: Maskable<String>) { self.headers.insert((String::from(header), value)); } pub fn add_certificate(&mut self, certificate: Option<Secret<String>>) { self.certificate = certificate; } pub fn add_certificate_key(&mut self, certificate_key: Option<Secret<String>>) { self.certificate = certificate_key; } } #[derive(Debug)] pub struct RequestBuilder { pub url: String, pub headers: Headers, pub method: Method, pub certificate: Option<Secret<String>>, pub certificate_key: Option<Secret<String>>, pub body: Option<RequestContent>, pub ca_certificate: Option<Secret<String>>, } impl RequestBuilder { pub fn new() -> Self { Self { method: Method::Get, url: String::with_capacity(1024), headers: std::collections::HashSet::new(), certificate: None, certificate_key: None, body: None, ca_certificate: None, } } pub fn url(mut self, url: &str) -> Self { self.url = url.into(); self } pub fn method(mut self, method: Method) -> Self { self.method = method; self } pub fn attach_default_headers(mut self) -> Self { self.headers.extend(default_request_headers()); self } pub fn header(mut self, header: &str, value: &str) -> Self { self.headers.insert((header.into(), value.into())); self } pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self { self.headers.extend(headers); self } pub fn set_optional_body<T: Into<RequestContent>>(mut self, body: Option<T>) -> Self { body.map(|body| self.body.replace(body.into())); self } pub fn set_body<T: Into<RequestContent>>(mut self, body: T) -> Self { self.body.replace(body.into()); self } pub fn add_certificate(mut self, certificate: Option<Secret<String>>) -> Self { self.certificate = certificate; self } pub fn add_certificate_key(mut self, certificate_key: Option<Secret<String>>) -> Self { self.certificate_key = certificate_key; self } pub fn add_ca_certificate_pem(mut self, ca_certificate: Option<Secret<String>>) -> Self { self.ca_certificate = ca_certificate; self } pub fn build(self) -> Request { Request { method: self.method, url: self.url, headers: self.headers, certificate: self.certificate, certificate_key: self.certificate_key, body: self.body, ca_certificate: self.ca_certificate, } } } impl Default for RequestBuilder { fn default() -> Self { Self::new() } }
crates/common_utils/src/request.rs
common_utils::src::request
1,351
true
// File: crates/common_utils/src/consts.rs // Module: common_utils::src::consts //! Commonly used constants /// Number of characters in a generated ID pub const ID_LENGTH: usize = 20; /// Characters to use for generating NanoID pub(crate) const ALPHABETS: [char; 62] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ]; /// TTL for token pub const TOKEN_TTL: i64 = 900; ///an example of the frm_configs json pub static FRM_CONFIGS_EG: &str = r#" [{"gateway":"stripe","payment_methods":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"credit","card_networks":["Visa"],"flow":"pre","action":"cancel_txn"},{"payment_method_type":"debit","card_networks":["Visa"],"flow":"pre"}]}]}] "#; /// Maximum limit for payments list get api pub const PAYMENTS_LIST_MAX_LIMIT_V1: u32 = 100; /// Maximum limit for payments list post api with filters pub const PAYMENTS_LIST_MAX_LIMIT_V2: u32 = 50; /// Default limit for payments list API pub fn default_payments_list_limit() -> u32 { 10 } /// Average delay (in seconds) between account onboarding's API response and the changes to actually reflect at Stripe's end pub const STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS: i64 = 15; /// Maximum limit for payment link list get api pub const PAYMENTS_LINK_LIST_LIMIT: u32 = 100; /// Maximum limit for payouts list get api pub const PAYOUTS_LIST_MAX_LIMIT_GET: u32 = 100; /// Maximum limit for payouts list post api pub const PAYOUTS_LIST_MAX_LIMIT_POST: u32 = 20; /// Default limit for payouts list API pub fn default_payouts_list_limit() -> u32 { 10 } /// surcharge percentage maximum precision length pub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2; /// Header Key for application overhead of a request pub const X_HS_LATENCY: &str = "x-hs-latency"; /// Redirect url for Prophetpay pub const PROPHETPAY_REDIRECT_URL: &str = "https://ccm-thirdparty.cps.golf/hp/tokenize/"; /// Variable which store the card token for Prophetpay pub const PROPHETPAY_TOKEN: &str = "cctoken"; /// Payment intent default client secret expiry (in seconds) pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; /// Payment intent fulfillment time (in seconds) pub const DEFAULT_INTENT_FULFILLMENT_TIME: i64 = 15 * 60; /// Payment order fulfillment time (in seconds) pub const DEFAULT_ORDER_FULFILLMENT_TIME: i64 = 15 * 60; /// Default ttl for Extended card info in redis (in seconds) pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60; /// Max ttl for Extended card info in redis (in seconds) pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2; /// Default tenant to be used when multitenancy is disabled pub const DEFAULT_TENANT: &str = "public"; /// Default tenant to be used when multitenancy is disabled pub const TENANT_HEADER: &str = "x-tenant-id"; /// Max Length for MerchantReferenceId pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64; /// Maximum length allowed for a global id pub const MIN_GLOBAL_ID_LENGTH: u8 = 32; /// Minimum length required for a global id pub const MAX_GLOBAL_ID_LENGTH: u8 = 64; /// Minimum allowed length for MerchantReferenceId pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1; /// Length of a cell identifier in a distributed system pub const CELL_IDENTIFIER_LENGTH: u8 = 5; /// General purpose base64 engine pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; /// URL Safe base64 engine pub const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE; /// URL Safe base64 engine without padding pub const BASE64_ENGINE_URL_SAFE_NO_PAD: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE_NO_PAD; /// Regex for matching a domain /// Eg - /// http://www.example.com /// https://www.example.com /// www.example.com /// example.io pub const STRICT_DOMAIN_REGEX: &str = r"^(https?://)?(([A-Za-z0-9][-A-Za-z0-9]\.)*[A-Za-z0-9][-A-Za-z0-9]*|(\d{1,3}\.){3}\d{1,3})+(:[0-9]{2,4})?$"; /// Regex for matching a wildcard domain /// Eg - /// *.example.com /// *.subdomain.domain.com /// *://example.com /// *example.com pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][-A-Za-z0-9]*\.)*[A-Za-z0-9][-A-Za-z0-9]*|((\d{1,3}|\*)\.){3}(\d{1,3}|\*)|\*)(:\*|:[0-9]{2,4})?(/\*)?$"; /// Maximum allowed length for MerchantName pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64; /// Default locale pub const DEFAULT_LOCALE: &str = "en"; /// Role ID for Tenant Admin pub const ROLE_ID_TENANT_ADMIN: &str = "tenant_admin"; /// Role ID for Org Admin pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin"; /// Role ID for Internal View Only pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only"; /// Role ID for Internal Admin pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin"; /// Role ID for Internal Demo pub const ROLE_ID_INTERNAL_DEMO: &str = "internal_demo"; /// Max length allowed for Description pub const MAX_DESCRIPTION_LENGTH: u16 = 255; /// Max length allowed for Statement Descriptor pub const MAX_STATEMENT_DESCRIPTOR_LENGTH: u16 = 22; /// Payout flow identifier used for performing GSM operations pub const PAYOUT_FLOW_STR: &str = "payout_flow"; /// length of the publishable key pub const PUBLISHABLE_KEY_LENGTH: u16 = 39; /// The number of bytes allocated for the hashed connector transaction ID. /// Total number of characters equals CONNECTOR_TRANSACTION_ID_HASH_BYTES times 2. pub const CONNECTOR_TRANSACTION_ID_HASH_BYTES: usize = 25; /// Apple Pay validation url pub const APPLEPAY_VALIDATION_URL: &str = "https://apple-pay-gateway-cert.apple.com/paymentservices/startSession"; /// Request ID pub const X_REQUEST_ID: &str = "x-request-id"; /// Flow name pub const X_FLOW_NAME: &str = "x-flow"; /// Connector name pub const X_CONNECTOR_NAME: &str = "x-connector"; /// Unified Connector Service Mode pub const X_UNIFIED_CONNECTOR_SERVICE_MODE: &str = "x-shadow-mode"; /// Chat Session ID pub const X_CHAT_SESSION_ID: &str = "x-chat-session-id"; /// Merchant ID Header pub const X_MERCHANT_ID: &str = "x-merchant-id"; /// Default Tenant ID for the `Global` tenant pub const DEFAULT_GLOBAL_TENANT_ID: &str = "global"; /// Default status of Card IP Blocking pub const DEFAULT_CARD_IP_BLOCKING_STATUS: bool = false; /// Default Threshold for Card IP Blocking pub const DEFAULT_CARD_IP_BLOCKING_THRESHOLD: i32 = 3; /// Default status of Guest User Card Blocking pub const DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS: bool = false; /// Default Threshold for Card Blocking for Guest Users pub const DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD: i32 = 10; /// Default status of Customer ID Blocking pub const DEFAULT_CUSTOMER_ID_BLOCKING_STATUS: bool = false; /// Default Threshold for Customer ID Blocking pub const DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD: i32 = 5; /// Default Card Testing Guard Redis Expiry in seconds pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600; /// SOAP 1.1 Envelope Namespace pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/"; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] /// Length of generated tokens pub const TOKEN_LENGTH: usize = 32; /// The tag name used for identifying the host in metrics. pub const METRICS_HOST_TAG_NAME: &str = "host"; /// API client request timeout (in seconds) pub const REQUEST_TIME_OUT: u64 = 30; /// API client request timeout for ai service (in seconds) pub const REQUEST_TIME_OUT_FOR_AI_SERVICE: u64 = 120; /// Default limit for list operations (can be used across different entities) pub const DEFAULT_LIST_LIMIT: i64 = 100; /// Default offset for list operations (can be used across different entities) pub const DEFAULT_LIST_OFFSET: i64 = 0;
crates/common_utils/src/consts.rs
common_utils::src::consts
2,289
true
// File: crates/common_utils/src/types.rs // Module: common_utils::src::types //! Types that can be used in other crates pub mod keymanager; /// Enum for Authentication Level pub mod authentication; /// User related types pub mod user; /// types that are wrappers around primitive types pub mod primitive_wrappers; use std::{ borrow::Cow, fmt::Display, iter::Sum, num::NonZeroI64, ops::{Add, Mul, Sub}, primitive::i64, str::FromStr, }; use common_enums::enums; use diesel::{ backend::Backend, deserialize, deserialize::FromSql, serialize::{Output, ToSql}, sql_types, sql_types::Jsonb, AsExpression, FromSqlRow, Queryable, }; use error_stack::{report, ResultExt}; pub use primitive_wrappers::bool_wrappers::{ AlwaysRequestExtendedAuthorization, ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use rust_decimal::{ prelude::{FromPrimitive, ToPrimitive}, Decimal, }; use semver::Version; use serde::{de::Visitor, Deserialize, Deserializer, Serialize}; use thiserror::Error; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{ consts::{ self, MAX_DESCRIPTION_LENGTH, MAX_STATEMENT_DESCRIPTOR_LENGTH, PUBLISHABLE_KEY_LENGTH, }, errors::{CustomResult, ParsingError, PercentageError, ValidationError}, fp_utils::when, id_type, impl_enum_str, }; /// Represents Percentage Value between 0 and 100 both inclusive #[derive(Clone, Default, Debug, PartialEq, Serialize)] pub struct Percentage<const PRECISION: u8> { // this value will range from 0 to 100, decimal length defined by precision macro /// Percentage value ranging between 0 and 100 percentage: f32, } fn get_invalid_percentage_error_message(precision: u8) -> String { format!( "value should be a float between 0 to 100 and precise to only upto {precision} decimal digits", ) } impl<const PRECISION: u8> Percentage<PRECISION> { /// construct percentage using a string representation of float value pub fn from_string(value: String) -> CustomResult<Self, PercentageError> { if Self::is_valid_string_value(&value)? { Ok(Self { percentage: value .parse::<f32>() .change_context(PercentageError::InvalidPercentageValue)?, }) } else { Err(report!(PercentageError::InvalidPercentageValue)) .attach_printable(get_invalid_percentage_error_message(PRECISION)) } } /// function to get percentage value pub fn get_percentage(&self) -> f32 { self.percentage } /// apply the percentage to amount and ceil the result #[allow(clippy::as_conversions)] pub fn apply_and_ceil_result( &self, amount: MinorUnit, ) -> CustomResult<MinorUnit, PercentageError> { let max_amount = i64::MAX / 10000; let amount = amount.0; if amount > max_amount { // value gets rounded off after i64::MAX/10000 Err(report!(PercentageError::UnableToApplyPercentage { percentage: self.percentage, amount: MinorUnit::new(amount), })) .attach_printable(format!( "Cannot calculate percentage for amount greater than {max_amount}", )) } else { let percentage_f64 = f64::from(self.percentage); let result = (amount as f64 * (percentage_f64 / 100.0)).ceil() as i64; Ok(MinorUnit::new(result)) } } fn is_valid_string_value(value: &str) -> CustomResult<bool, PercentageError> { let float_value = Self::is_valid_float_string(value)?; Ok(Self::is_valid_range(float_value) && Self::is_valid_precision_length(value)) } fn is_valid_float_string(value: &str) -> CustomResult<f32, PercentageError> { value .parse::<f32>() .change_context(PercentageError::InvalidPercentageValue) } fn is_valid_range(value: f32) -> bool { (0.0..=100.0).contains(&value) } fn is_valid_precision_length(value: &str) -> bool { if value.contains('.') { // if string has '.' then take the decimal part and verify precision length match value.split('.').next_back() { Some(decimal_part) => { decimal_part.trim_end_matches('0').len() <= <u8 as Into<usize>>::into(PRECISION) } // will never be None None => false, } } else { // if there is no '.' then it is a whole number with no decimal part. So return true true } } } // custom serde deserialization function struct PercentageVisitor<const PRECISION: u8> {} impl<'de, const PRECISION: u8> Visitor<'de> for PercentageVisitor<PRECISION> { type Value = Percentage<PRECISION>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Percentage object") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de>, { let mut percentage_value = None; while let Some(key) = map.next_key::<String>()? { if key.eq("percentage") { if percentage_value.is_some() { return Err(serde::de::Error::duplicate_field("percentage")); } percentage_value = Some(map.next_value::<serde_json::Value>()?); } else { // Ignore unknown fields let _: serde::de::IgnoredAny = map.next_value()?; } } if let Some(value) = percentage_value { let string_value = value.to_string(); Ok(Percentage::from_string(string_value.clone()).map_err(|_| { serde::de::Error::invalid_value( serde::de::Unexpected::Other(&format!("percentage value {string_value}")), &&*get_invalid_percentage_error_message(PRECISION), ) })?) } else { Err(serde::de::Error::missing_field("percentage")) } } } impl<'de, const PRECISION: u8> Deserialize<'de> for Percentage<PRECISION> { fn deserialize<D>(data: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { data.deserialize_map(PercentageVisitor::<PRECISION> {}) } } /// represents surcharge type and value #[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum Surcharge { /// Fixed Surcharge value Fixed(MinorUnit), /// Surcharge percentage Rate(Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>), } /// This struct lets us represent a semantic version type #[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, Ord, PartialOrd)] #[diesel(sql_type = Jsonb)] #[derive(Serialize, serde::Deserialize)] pub struct SemanticVersion(#[serde(with = "Version")] Version); impl SemanticVersion { /// returns major version number pub fn get_major(&self) -> u64 { self.0.major } /// returns minor version number pub fn get_minor(&self) -> u64 { self.0.minor } /// Constructs new SemanticVersion instance pub fn new(major: u64, minor: u64, patch: u64) -> Self { Self(Version::new(major, minor, patch)) } } impl Display for SemanticVersion { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl FromStr for SemanticVersion { type Err = error_stack::Report<ParsingError>; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self(Version::from_str(s).change_context( ParsingError::StructParseFailure("SemanticVersion"), )?)) } } crate::impl_to_sql_from_sql_json!(SemanticVersion); /// Amount convertor trait for connector pub trait AmountConvertor: Send { /// Output type for the connector type Output; /// helps in conversion of connector required amount type fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>>; /// helps in converting back connector required amount type to core minor unit fn convert_back( &self, amount: Self::Output, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>>; } /// Connector required amount type #[derive(Default, Debug, Clone, Copy, PartialEq)] pub struct StringMinorUnitForConnector; impl AmountConvertor for StringMinorUnitForConnector { type Output = StringMinorUnit; fn convert( &self, amount: MinorUnit, _currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_string() } fn convert_back( &self, amount: Self::Output, _currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64() } } /// Core required conversion type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct StringMajorUnitForCore; impl AmountConvertor for StringMajorUnitForCore { type Output = StringMajorUnit; fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_major_unit_as_string(currency) } fn convert_back( &self, amount: StringMajorUnit, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64(currency) } } /// Connector required amount type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct StringMajorUnitForConnector; impl AmountConvertor for StringMajorUnitForConnector { type Output = StringMajorUnit; fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_major_unit_as_string(currency) } fn convert_back( &self, amount: StringMajorUnit, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64(currency) } } /// Connector required amount type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct FloatMajorUnitForConnector; impl AmountConvertor for FloatMajorUnitForConnector { type Output = FloatMajorUnit; fn convert( &self, amount: MinorUnit, currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { amount.to_major_unit_as_f64(currency) } fn convert_back( &self, amount: FloatMajorUnit, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { amount.to_minor_unit_as_i64(currency) } } /// Connector required amount type #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct MinorUnitForConnector; impl AmountConvertor for MinorUnitForConnector { type Output = MinorUnit; fn convert( &self, amount: MinorUnit, _currency: enums::Currency, ) -> Result<Self::Output, error_stack::Report<ParsingError>> { Ok(amount) } fn convert_back( &self, amount: MinorUnit, _currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { Ok(amount) } } /// This Unit struct represents MinorUnit in which core amount works #[derive( Default, Debug, serde::Deserialize, AsExpression, serde::Serialize, Clone, Copy, PartialEq, Eq, Hash, ToSchema, PartialOrd, )] #[diesel(sql_type = sql_types::BigInt)] pub struct MinorUnit(i64); impl MinorUnit { /// gets amount as i64 value will be removed in future pub fn get_amount_as_i64(self) -> i64 { self.0 } /// forms a new minor default unit i.e zero pub fn zero() -> Self { Self(0) } /// forms a new minor unit from amount pub fn new(value: i64) -> Self { Self(value) } /// checks if the amount is greater than the given value pub fn is_greater_than(&self, value: i64) -> bool { self.get_amount_as_i64() > value } /// Convert the amount to its major denomination based on Currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ fn to_major_unit_as_string( self, currency: enums::Currency, ) -> Result<StringMajorUnit, error_stack::Report<ParsingError>> { let amount_f64 = self.to_major_unit_as_f64(currency)?; let amount_string = if currency.is_zero_decimal_currency() { amount_f64.0.to_string() } else if currency.is_three_decimal_currency() { format!("{:.3}", amount_f64.0) } else { format!("{:.2}", amount_f64.0) }; Ok(StringMajorUnit::new(amount_string)) } /// Convert the amount to its major denomination based on Currency and return f64 fn to_major_unit_as_f64( self, currency: enums::Currency, ) -> Result<FloatMajorUnit, error_stack::Report<ParsingError>> { let amount_decimal = Decimal::from_i64(self.0).ok_or(ParsingError::I64ToDecimalConversionFailure)?; let amount = if currency.is_zero_decimal_currency() { amount_decimal } else if currency.is_three_decimal_currency() { amount_decimal / Decimal::from(1000) } else { amount_decimal / Decimal::from(100) }; let amount_f64 = amount .to_f64() .ok_or(ParsingError::FloatToDecimalConversionFailure)?; Ok(FloatMajorUnit::new(amount_f64)) } ///Convert minor unit to string minor unit fn to_minor_unit_as_string(self) -> Result<StringMinorUnit, error_stack::Report<ParsingError>> { Ok(StringMinorUnit::new(self.0.to_string())) } } impl From<NonZeroI64> for MinorUnit { fn from(val: NonZeroI64) -> Self { Self::new(val.get()) } } impl Display for MinorUnit { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl<DB> FromSql<sql_types::BigInt, DB> for MinorUnit where DB: Backend, i64: FromSql<sql_types::BigInt, DB>, { fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = i64::from_sql(value)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::BigInt, DB> for MinorUnit where DB: Backend, i64: ToSql<sql_types::BigInt, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> Queryable<sql_types::BigInt, DB> for MinorUnit where DB: Backend, Self: FromSql<sql_types::BigInt, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl Add for MinorUnit { type Output = Self; fn add(self, a2: Self) -> Self { Self(self.0 + a2.0) } } impl Sub for MinorUnit { type Output = Self; fn sub(self, a2: Self) -> Self { Self(self.0 - a2.0) } } impl Mul<u16> for MinorUnit { type Output = Self; fn mul(self, a2: u16) -> Self::Output { Self(self.0 * i64::from(a2)) } } impl Sum for MinorUnit { fn sum<I: Iterator<Item = Self>>(iter: I) -> Self { iter.fold(Self(0), |a, b| a + b) } } /// Connector specific types to send #[derive( Default, Debug, serde::Deserialize, AsExpression, serde::Serialize, Clone, PartialEq, Eq, Hash, ToSchema, PartialOrd, )] #[diesel(sql_type = sql_types::Text)] pub struct StringMinorUnit(String); impl StringMinorUnit { /// forms a new minor unit in string from amount fn new(value: String) -> Self { Self(value) } /// converts to minor unit i64 from minor unit string value fn to_minor_unit_as_i64(&self) -> Result<MinorUnit, error_stack::Report<ParsingError>> { let amount_string = &self.0; let amount_decimal = Decimal::from_str(amount_string).map_err(|e| { ParsingError::StringToDecimalConversionFailure { error: e.to_string(), } })?; let amount_i64 = amount_decimal .to_i64() .ok_or(ParsingError::DecimalToI64ConversionFailure)?; Ok(MinorUnit::new(amount_i64)) } } impl Display for StringMinorUnit { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl<DB> FromSql<sql_types::Text, DB> for StringMinorUnit where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(value)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::Text, DB> for StringMinorUnit where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> Queryable<sql_types::Text, DB> for StringMinorUnit where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } /// Connector specific types to send #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct FloatMajorUnit(f64); impl FloatMajorUnit { /// forms a new major unit from amount fn new(value: f64) -> Self { Self(value) } /// forms a new major unit with zero amount pub fn zero() -> Self { Self(0.0) } /// converts to minor unit as i64 from FloatMajorUnit fn to_minor_unit_as_i64( self, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { let amount_decimal = Decimal::from_f64(self.0).ok_or(ParsingError::FloatToDecimalConversionFailure)?; let amount = if currency.is_zero_decimal_currency() { amount_decimal } else if currency.is_three_decimal_currency() { amount_decimal * Decimal::from(1000) } else { amount_decimal * Decimal::from(100) }; let amount_i64 = amount .to_i64() .ok_or(ParsingError::DecimalToI64ConversionFailure)?; Ok(MinorUnit::new(amount_i64)) } } /// Connector specific types to send #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)] pub struct StringMajorUnit(String); impl StringMajorUnit { /// forms a new major unit from amount fn new(value: String) -> Self { Self(value) } /// Converts to minor unit as i64 from StringMajorUnit fn to_minor_unit_as_i64( &self, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<ParsingError>> { let amount_decimal = Decimal::from_str(&self.0).map_err(|e| { ParsingError::StringToDecimalConversionFailure { error: e.to_string(), } })?; let amount = if currency.is_zero_decimal_currency() { amount_decimal } else if currency.is_three_decimal_currency() { amount_decimal * Decimal::from(1000) } else { amount_decimal * Decimal::from(100) }; let amount_i64 = amount .to_i64() .ok_or(ParsingError::DecimalToI64ConversionFailure)?; Ok(MinorUnit::new(amount_i64)) } /// forms a new StringMajorUnit default unit i.e zero pub fn zero() -> Self { Self("0".to_string()) } /// Get string amount from struct to be removed in future pub fn get_amount_as_string(&self) -> String { self.0.clone() } } #[derive( Debug, serde::Deserialize, AsExpression, serde::Serialize, Clone, PartialEq, Eq, Hash, ToSchema, PartialOrd, )] #[diesel(sql_type = sql_types::Text)] /// This domain type can be used for any url pub struct Url(url::Url); impl Url { /// Get string representation of the url pub fn get_string_repr(&self) -> &str { self.0.as_str() } /// wrap the url::Url in Url type pub fn wrap(url: url::Url) -> Self { Self(url) } /// Get the inner url pub fn into_inner(self) -> url::Url { self.0 } /// Add query params to the url pub fn add_query_params(mut self, (key, value): (&str, &str)) -> Self { let url = self .0 .query_pairs_mut() .append_pair(key, value) .finish() .clone(); Self(url) } } impl<DB> ToSql<sql_types::Text, DB> for Url where DB: Backend, str: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { let url_string = self.0.as_str(); url_string.to_sql(out) } } impl<DB> FromSql<sql_types::Text, DB> for Url where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(value)?; let url = url::Url::parse(&val)?; Ok(Self(url)) } } /// A type representing a range of time for filtering, including a mandatory start time and an optional end time. #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, )] pub struct TimeRange { /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed #[serde(with = "crate::custom_serde::iso8601")] #[serde(alias = "startTime")] pub start_time: PrimitiveDateTime, /// The end time to filter payments list or to get list of filters. If not passed the default time is now #[serde(default, with = "crate::custom_serde::iso8601::option")] #[serde(alias = "endTime")] pub end_time: Option<PrimitiveDateTime>, } #[cfg(test)] mod amount_conversion_tests { #![allow(clippy::unwrap_used)] use super::*; const TWO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::USD; const THREE_DECIMAL_CURRENCY: enums::Currency = enums::Currency::BHD; const ZERO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::JPY; #[test] fn amount_conversion_to_float_major_unit() { let request_amount = MinorUnit::new(999999999); let required_conversion = FloatMajorUnitForConnector; // Two decimal currency conversions let converted_amount = required_conversion .convert(request_amount, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, 9999999.99); let converted_back_amount = required_conversion .convert_back(converted_amount, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Three decimal currency conversions let converted_amount = required_conversion .convert(request_amount, THREE_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, 999999.999); let converted_back_amount = required_conversion .convert_back(converted_amount, THREE_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Zero decimal currency conversions let converted_amount = required_conversion .convert(request_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, 999999999.0); let converted_back_amount = required_conversion .convert_back(converted_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); } #[test] fn amount_conversion_to_string_major_unit() { let request_amount = MinorUnit::new(999999999); let required_conversion = StringMajorUnitForConnector; // Two decimal currency conversions let converted_amount_two_decimal_currency = required_conversion .convert(request_amount, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!( converted_amount_two_decimal_currency.0, "9999999.99".to_string() ); let converted_back_amount = required_conversion .convert_back(converted_amount_two_decimal_currency, TWO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Three decimal currency conversions let converted_amount_three_decimal_currency = required_conversion .convert(request_amount, THREE_DECIMAL_CURRENCY) .unwrap(); assert_eq!( converted_amount_three_decimal_currency.0, "999999.999".to_string() ); let converted_back_amount = required_conversion .convert_back( converted_amount_three_decimal_currency, THREE_DECIMAL_CURRENCY, ) .unwrap(); assert_eq!(converted_back_amount, request_amount); // Zero decimal currency conversions let converted_amount = required_conversion .convert(request_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_amount.0, "999999999".to_string()); let converted_back_amount = required_conversion .convert_back(converted_amount, ZERO_DECIMAL_CURRENCY) .unwrap(); assert_eq!(converted_back_amount, request_amount); } #[test] fn amount_conversion_to_string_minor_unit() { let request_amount = MinorUnit::new(999999999); let currency = TWO_DECIMAL_CURRENCY; let required_conversion = StringMinorUnitForConnector; let converted_amount = required_conversion .convert(request_amount, currency) .unwrap(); assert_eq!(converted_amount.0, "999999999".to_string()); let converted_back_amount = required_conversion .convert_back(converted_amount, currency) .unwrap(); assert_eq!(converted_back_amount, request_amount); } } // Charges structs #[derive( Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] /// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details. pub struct ChargeRefunds { /// Identifier for charge created for the payment pub charge_id: String, /// Toggle for reverting the application fee that was collected for the payment. /// If set to false, the funds are pulled from the destination account. pub revert_platform_fee: Option<bool>, /// Toggle for reverting the transfer that was made during the charge. /// If set to false, the funds are pulled from the main platform's account. pub revert_transfer: Option<bool>, } crate::impl_to_sql_from_sql_json!(ChargeRefunds); /// A common type of domain type that can be used for fields that contain a string with restriction of length #[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub(crate) struct LengthString<const MAX_LENGTH: u16, const MIN_LENGTH: u16>(String); /// Error generated from violation of constraints for MerchantReferenceId #[derive(Debug, Error, PartialEq, Eq)] pub(crate) enum LengthStringError { #[error("the maximum allowed length for this field is {0}")] /// Maximum length of string violated MaxLengthViolated(u16), #[error("the minimum required length for this field is {0}")] /// Minimum length of string violated MinLengthViolated(u16), } impl<const MAX_LENGTH: u16, const MIN_LENGTH: u16> LengthString<MAX_LENGTH, MIN_LENGTH> { /// Generates new [MerchantReferenceId] from the given input string pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthStringError> { let trimmed_input_string = input_string.trim().to_string(); let length_of_input_string = u16::try_from(trimmed_input_string.len()) .map_err(|_| LengthStringError::MaxLengthViolated(MAX_LENGTH))?; when(length_of_input_string > MAX_LENGTH, || { Err(LengthStringError::MaxLengthViolated(MAX_LENGTH)) })?; when(length_of_input_string < MIN_LENGTH, || { Err(LengthStringError::MinLengthViolated(MIN_LENGTH)) })?; Ok(Self(trimmed_input_string)) } pub(crate) fn new_unchecked(input_string: String) -> Self { Self(input_string) } } impl<'de, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Deserialize<'de> for LengthString<MAX_LENGTH, MIN_LENGTH> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from(deserialized_string.into()).map_err(serde::de::Error::custom) } } impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> FromSql<sql_types::Text, DB> for LengthString<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self(val)) } } impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> ToSql<sql_types::Text, DB> for LengthString<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Queryable<sql_types::Text, DB> for LengthString<MAX_LENGTH, MIN_LENGTH> where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } /// Domain type for description #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub struct Description(LengthString<MAX_DESCRIPTION_LENGTH, 1>); impl Description { /// Create a new Description Domain type without any length check from a static str pub fn from_str_unchecked(input_str: &'static str) -> Self { Self(LengthString::new_unchecked(input_str.to_owned())) } // TODO: Remove this function in future once description in router data is updated to domain type /// Get the string representation of the description pub fn get_string_repr(&self) -> &str { &self.0 .0 } } /// Domain type for Statement Descriptor #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub struct StatementDescriptor(LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>); impl<DB> Queryable<sql_types::Text, DB> for Description where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for Description where DB: Backend, LengthString<MAX_DESCRIPTION_LENGTH, 1>: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = LengthString::<MAX_DESCRIPTION_LENGTH, 1>::from_sql(bytes)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::Text, DB> for Description where DB: Backend, LengthString<MAX_DESCRIPTION_LENGTH, 1>: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> Queryable<sql_types::Text, DB> for StatementDescriptor where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for StatementDescriptor where DB: Backend, LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = LengthString::<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>::from_sql(bytes)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::Text, DB> for StatementDescriptor where DB: Backend, LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } /// Domain type for unified code #[derive( Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression, )] #[diesel(sql_type = sql_types::Text)] pub struct UnifiedCode(pub String); impl TryFrom<String> for UnifiedCode { type Error = error_stack::Report<ValidationError>; fn try_from(src: String) -> Result<Self, Self::Error> { if src.len() > 255 { Err(report!(ValidationError::InvalidValue { message: "unified_code's length should not exceed 255 characters".to_string() })) } else { Ok(Self(src)) } } } impl<DB> Queryable<sql_types::Text, DB> for UnifiedCode where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for UnifiedCode where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self::try_from(val)?) } } impl<DB> ToSql<sql_types::Text, DB> for UnifiedCode where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } /// Domain type for unified messages #[derive( Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression, )] #[diesel(sql_type = sql_types::Text)] pub struct UnifiedMessage(pub String); impl TryFrom<String> for UnifiedMessage { type Error = error_stack::Report<ValidationError>; fn try_from(src: String) -> Result<Self, Self::Error> { if src.len() > 1024 { Err(report!(ValidationError::InvalidValue { message: "unified_message's length should not exceed 1024 characters".to_string() })) } else { Ok(Self(src)) } } } impl<DB> Queryable<sql_types::Text, DB> for UnifiedMessage where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for UnifiedMessage where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self::try_from(val)?) } } impl<DB> ToSql<sql_types::Text, DB> for UnifiedMessage where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } #[cfg(feature = "v2")] /// Browser information to be used for 3DS 2.0 // If any of the field is PII, then we can make them as secret #[derive( ToSchema, Debug, Clone, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression, )] #[diesel(sql_type = Jsonb)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, /// Accept-language of the browser pub accept_language: Option<String>, /// Identifier of the source that initiated the request. pub referer: Option<String>, } #[cfg(feature = "v2")] crate::impl_to_sql_from_sql_json!(BrowserInformation); /// Domain type for connector_transaction_id /// Maximum length for connector's transaction_id can be 128 characters in HS DB. /// In case connector's use an identifier whose length exceeds 128 characters, /// the hash value of such identifiers will be stored as connector_transaction_id. /// The actual connector's identifier will be stored in a separate column - /// processor_transaction_data or something with a similar name. #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub enum ConnectorTransactionId { /// Actual transaction identifier TxnId(String), /// Hashed value of the transaction identifier HashedData(String), } impl ConnectorTransactionId { /// Implementation for retrieving the inner identifier pub fn get_id(&self) -> &String { match self { Self::TxnId(id) | Self::HashedData(id) => id, } } /// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and processor_transaction_data pub fn form_id_and_data(src: String) -> (Self, Option<String>) { let txn_id = Self::from(src.clone()); match txn_id { Self::TxnId(_) => (txn_id, None), Self::HashedData(_) => (txn_id, Some(src)), } } /// Implementation for extracting hashed data pub fn extract_hashed_data(&self) -> Option<String> { match self { Self::TxnId(_) => None, Self::HashedData(src) => Some(src.clone()), } } /// Implementation for retrieving pub fn get_txn_id<'a>( &'a self, txn_data: Option<&'a String>, ) -> Result<&'a String, error_stack::Report<ValidationError>> { match (self, txn_data) { (Self::TxnId(id), _) => Ok(id), (Self::HashedData(_), Some(id)) => Ok(id), (Self::HashedData(id), None) => Err(report!(ValidationError::InvalidValue { message: "processor_transaction_data is empty for HashedData variant".to_string(), }) .attach_printable(format!( "processor_transaction_data is empty for connector_transaction_id {id}", ))), } } } impl From<String> for ConnectorTransactionId { fn from(src: String) -> Self { // ID already hashed if src.starts_with("hs_hash_") { Self::HashedData(src) // Hash connector's transaction ID } else if src.len() > 128 { let mut hasher = blake3::Hasher::new(); let mut output = [0u8; consts::CONNECTOR_TRANSACTION_ID_HASH_BYTES]; hasher.update(src.as_bytes()); hasher.finalize_xof().fill(&mut output); let hash = hex::encode(output); Self::HashedData(format!("hs_hash_{hash}")) // Default } else { Self::TxnId(src) } } } impl<DB> Queryable<sql_types::Text, DB> for ConnectorTransactionId where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for ConnectorTransactionId where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self::from(val)) } } impl<DB> ToSql<sql_types::Text, DB> for ConnectorTransactionId where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { match self { Self::HashedData(id) | Self::TxnId(id) => id.to_sql(out), } } } /// Trait for fetching actual or hashed transaction IDs pub trait ConnectorTransactionIdTrait { /// Returns an optional connector transaction ID fn get_optional_connector_transaction_id(&self) -> Option<&String> { None } /// Returns a connector transaction ID fn get_connector_transaction_id(&self) -> &String { self.get_optional_connector_transaction_id() .unwrap_or_else(|| { static EMPTY_STRING: String = String::new(); &EMPTY_STRING }) } /// Returns an optional connector refund ID fn get_optional_connector_refund_id(&self) -> Option<&String> { self.get_optional_connector_transaction_id() } } /// Domain type for PublishableKey #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub struct PublishableKey(LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>); impl PublishableKey { /// Create a new PublishableKey Domain type without any length check from a static str pub fn generate(env_prefix: &'static str) -> Self { let publishable_key_string = format!("pk_{env_prefix}_{}", uuid::Uuid::now_v7().simple()); Self(LengthString::new_unchecked(publishable_key_string)) } /// Get the string representation of the PublishableKey pub fn get_string_repr(&self) -> &str { &self.0 .0 } } impl<DB> Queryable<sql_types::Text, DB> for PublishableKey where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for PublishableKey where DB: Backend, LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = LengthString::<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>::from_sql(bytes)?; Ok(Self(val)) } } impl<DB> ToSql<sql_types::Text, DB> for PublishableKey where DB: Backend, LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl_enum_str!( tag_delimiter = ":", /// CreatedBy conveys the information about the creator (identifier) as well as the origin or /// trigger (Api, Jwt) of the record. #[derive(Eq, PartialEq, Debug, Clone)] pub enum CreatedBy { /// Api variant Api { /// merchant id of creator. merchant_id: String, }, /// Jwt variant Jwt { /// user id of creator. user_id: String, }, } ); #[allow(missing_docs)] pub trait TenantConfig: Send + Sync { fn get_tenant_id(&self) -> &id_type::TenantId; fn get_schema(&self) -> &str; fn get_accounts_schema(&self) -> &str; fn get_redis_key_prefix(&self) -> &str; fn get_clickhouse_database(&self) -> &str; }
crates/common_utils/src/types.rs
common_utils::src::types
11,061
true
// File: crates/common_utils/src/events.rs // Module: common_utils::src::events use serde::Serialize; use crate::{id_type, types::TimeRange}; pub trait ApiEventMetric { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(tag = "flow_type", rename_all = "snake_case")] pub enum ApiEventsType { Payout { payout_id: id_type::PayoutId, }, #[cfg(feature = "v1")] Payment { payment_id: id_type::PaymentId, }, #[cfg(feature = "v2")] Payment { payment_id: id_type::GlobalPaymentId, }, #[cfg(feature = "v1")] Refund { payment_id: Option<id_type::PaymentId>, refund_id: String, }, #[cfg(feature = "v2")] Refund { payment_id: Option<id_type::GlobalPaymentId>, refund_id: id_type::GlobalRefundId, }, #[cfg(feature = "v1")] PaymentMethod { payment_method_id: String, payment_method: Option<common_enums::PaymentMethod>, payment_method_type: Option<common_enums::PaymentMethodType>, }, #[cfg(feature = "v2")] PaymentMethod { payment_method_id: id_type::GlobalPaymentMethodId, payment_method_type: Option<common_enums::PaymentMethod>, payment_method_subtype: Option<common_enums::PaymentMethodType>, }, #[cfg(feature = "v2")] PaymentMethodCreate, #[cfg(feature = "v2")] Customer { customer_id: Option<id_type::GlobalCustomerId>, }, #[cfg(feature = "v1")] Customer { customer_id: id_type::CustomerId, }, BusinessProfile { profile_id: id_type::ProfileId, }, ApiKey { key_id: id_type::ApiKeyId, }, User { user_id: String, }, PaymentMethodList { payment_id: Option<String>, }, #[cfg(feature = "v2")] PaymentMethodListForPaymentMethods { payment_method_id: id_type::GlobalPaymentMethodId, }, #[cfg(feature = "v1")] Webhooks { connector: String, payment_id: Option<id_type::PaymentId>, }, #[cfg(feature = "v1")] NetworkTokenWebhook { payment_method_id: Option<String>, }, #[cfg(feature = "v2")] Webhooks { connector: id_type::MerchantConnectorAccountId, payment_id: Option<id_type::GlobalPaymentId>, }, Routing, Subscription, Invoice, ResourceListAPI, #[cfg(feature = "v1")] PaymentRedirectionResponse { connector: Option<String>, payment_id: Option<id_type::PaymentId>, }, #[cfg(feature = "v2")] PaymentRedirectionResponse { payment_id: id_type::GlobalPaymentId, }, Gsm, // TODO: This has to be removed once the corresponding apiEventTypes are created Miscellaneous, Keymanager, RustLocker, ApplePayCertificatesMigration, FraudCheck, Recon, ExternalServiceAuth, Dispute { dispute_id: String, }, Events { merchant_id: id_type::MerchantId, }, PaymentMethodCollectLink { link_id: String, }, Poll { poll_id: String, }, Analytics, #[cfg(feature = "v2")] ClientSecret { key_id: id_type::ClientSecretId, }, #[cfg(feature = "v2")] PaymentMethodSession { payment_method_session_id: id_type::GlobalPaymentMethodSessionId, }, #[cfg(feature = "v2")] Token { token_id: Option<id_type::GlobalTokenId>, }, ProcessTracker, Authentication { authentication_id: id_type::AuthenticationId, }, ProfileAcquirer { profile_acquirer_id: id_type::ProfileAcquirerId, }, ThreeDsDecisionRule, Chat, } impl ApiEventMetric for serde_json::Value {} impl ApiEventMetric for () {} #[cfg(feature = "v1")] impl ApiEventMetric for id_type::PaymentId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for id_type::GlobalPaymentId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.clone(), }) } } impl<Q: ApiEventMetric, E> ApiEventMetric for Result<Q, E> { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self { Ok(q) => q.get_api_event_type(), Err(_) => None, } } } // TODO: Ideally all these types should be replaced by newtype responses impl<T> ApiEventMetric for Vec<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } #[macro_export] macro_rules! impl_api_event_type { ($event: ident, ($($type:ty),+))=> { $( impl ApiEventMetric for $type { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::$event) } } )+ }; } impl_api_event_type!( Miscellaneous, ( String, id_type::MerchantId, (Option<i64>, Option<i64>, String), (Option<i64>, Option<i64>, id_type::MerchantId), bool ) ); impl<T: ApiEventMetric> ApiEventMetric for &T { fn get_api_event_type(&self) -> Option<ApiEventsType> { T::get_api_event_type(self) } } impl ApiEventMetric for TimeRange {}
crates/common_utils/src/events.rs
common_utils::src::events
1,339
true
// File: crates/common_utils/src/encryption.rs // Module: common_utils::src::encryption use diesel::{ backend::Backend, deserialize::{self, FromSql, Queryable}, expression::AsExpression, serialize::ToSql, sql_types, }; use masking::Secret; use crate::{crypto::Encryptable, pii::EncryptionStrategy}; impl<DB> FromSql<sql_types::Binary, DB> for Encryption where DB: Backend, Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { <Secret<Vec<u8>, EncryptionStrategy>>::from_sql(bytes).map(Self::new) } } impl<DB> ToSql<sql_types::Binary, DB> for Encryption where DB: Backend, Secret<Vec<u8>, EncryptionStrategy>: ToSql<sql_types::Binary, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.get_inner().to_sql(out) } } impl<DB> Queryable<sql_types::Binary, DB> for Encryption where DB: Backend, Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>, { type Row = Secret<Vec<u8>, EncryptionStrategy>; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(Self { inner: row }) } } #[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] #[diesel(sql_type = sql_types::Binary)] #[repr(transparent)] pub struct Encryption { inner: Secret<Vec<u8>, EncryptionStrategy>, } impl<T: Clone> From<Encryptable<T>> for Encryption { fn from(value: Encryptable<T>) -> Self { Self::new(value.into_encrypted()) } } impl Encryption { pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self { Self { inner: item } } #[inline] pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.inner } #[inline] pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> { &self.inner } }
crates/common_utils/src/encryption.rs
common_utils::src::encryption
516
true
// File: crates/common_utils/src/transformers.rs // Module: common_utils::src::transformers //! Utilities for converting between foreign types /// Trait for converting from one foreign type to another pub trait ForeignFrom<F> { /// Convert from a foreign type to the current type fn foreign_from(from: F) -> Self; } /// Trait for converting from one foreign type to another pub trait ForeignTryFrom<F>: Sized { /// Custom error for conversion failure type Error; /// Convert from a foreign type to the current type and return an error if the conversion fails fn foreign_try_from(from: F) -> Result<Self, Self::Error>; }
crates/common_utils/src/transformers.rs
common_utils::src::transformers
143
true
// File: crates/common_utils/src/lib.rs // Module: common_utils::src::lib #![warn(missing_docs, missing_debug_implementations)] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] use masking::{PeekInterface, Secret}; pub mod access_token; pub mod consts; pub mod crypto; pub mod custom_serde; #[allow(missing_docs)] // Todo: add docs pub mod encryption; pub mod errors; #[allow(missing_docs)] // Todo: add docs pub mod events; pub mod ext_traits; pub mod fp_utils; /// Used for hashing pub mod hashing; pub mod id_type; #[cfg(feature = "keymanager")] pub mod keymanager; pub mod link_utils; pub mod macros; #[cfg(feature = "metrics")] pub mod metrics; pub mod new_type; pub mod payout_method_utils; pub mod pii; #[allow(missing_docs)] // Todo: add docs pub mod request; #[cfg(feature = "signals")] pub mod signals; pub mod transformers; pub mod types; /// Unified Connector Service (UCS) interface definitions. /// /// This module defines types and traits for interacting with the Unified Connector Service. /// It includes reference ID types for payments and refunds, and a trait for extracting /// UCS reference information from requests. pub mod ucs_types; pub mod validation; pub use base64_serializer::Base64Serializer; /// Date-time utilities. pub mod date_time { #[cfg(feature = "async_ext")] use std::time::Instant; use std::{marker::PhantomData, num::NonZeroU8}; use masking::{Deserialize, Serialize}; use time::{ format_description::{ well_known::iso8601::{Config, EncodedConfig, Iso8601, TimePrecision}, BorrowedFormatItem, }, OffsetDateTime, PrimitiveDateTime, }; /// Enum to represent date formats #[derive(Debug)] pub enum DateFormat { /// Format the date in 20191105081132 format YYYYMMDDHHmmss, /// Format the date in 20191105 format YYYYMMDD, /// Format the date in 201911050811 format YYYYMMDDHHmm, /// Format the date in 05112019081132 format DDMMYYYYHHmmss, } /// Create a new [`PrimitiveDateTime`] with the current date and time in UTC. pub fn now() -> PrimitiveDateTime { let utc_date_time = OffsetDateTime::now_utc(); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) } /// Convert from OffsetDateTime to PrimitiveDateTime pub fn convert_to_pdt(offset_time: OffsetDateTime) -> PrimitiveDateTime { PrimitiveDateTime::new(offset_time.date(), offset_time.time()) } /// Return the UNIX timestamp of the current date and time in UTC pub fn now_unix_timestamp() -> i64 { OffsetDateTime::now_utc().unix_timestamp() } /// Calculate execution time for a async block in milliseconds #[cfg(feature = "async_ext")] pub async fn time_it<T, Fut: futures::Future<Output = T>, F: FnOnce() -> Fut>( block: F, ) -> (T, f64) { let start = Instant::now(); let result = block().await; (result, start.elapsed().as_secs_f64() * 1000f64) } /// Return the given date and time in UTC with the given format Eg: format: YYYYMMDDHHmmss Eg: 20191105081132 pub fn format_date( date: PrimitiveDateTime, format: DateFormat, ) -> Result<String, time::error::Format> { let format = <&[BorrowedFormatItem<'_>]>::from(format); date.format(&format) } /// Return the current date and time in UTC with the format [year]-[month]-[day]T[hour]:[minute]:[second].mmmZ Eg: 2023-02-15T13:33:18.898Z pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> { const ISO_CONFIG: EncodedConfig = Config::DEFAULT .set_time_precision(TimePrecision::Second { decimal_digits: NonZeroU8::new(3), }) .encode(); now().assume_utc().format(&Iso8601::<ISO_CONFIG>) } /// Return the current date and time in UTC formatted as "ddd, DD MMM YYYY HH:mm:ss GMT". pub fn now_rfc7231_http_date() -> Result<String, time::error::Format> { let now_utc = OffsetDateTime::now_utc(); // Desired format: ddd, DD MMM YYYY HH:mm:ss GMT // Example: Fri, 23 May 2025 06:19:35 GMT let format = time::macros::format_description!( "[weekday repr:short], [day padding:zero] [month repr:short] [year repr:full] [hour padding:zero repr:24]:[minute padding:zero]:[second padding:zero] GMT" ); now_utc.format(&format) } impl From<DateFormat> for &[BorrowedFormatItem<'_>] { fn from(format: DateFormat) -> Self { match format { DateFormat::YYYYMMDDHHmmss => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero][second padding:zero]"), DateFormat::YYYYMMDD => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero]"), DateFormat::YYYYMMDDHHmm => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero]"), DateFormat::DDMMYYYYHHmmss => time::macros::format_description!("[day padding:zero][month padding:zero repr:numerical][year repr:full][hour padding:zero repr:24][minute padding:zero][second padding:zero]"), } } } /// Format the date in 05112019 format #[derive(Debug, Clone)] pub struct DDMMYYYY; /// Format the date in 20191105 format #[derive(Debug, Clone)] pub struct YYYYMMDD; /// Format the date in 20191105081132 format #[derive(Debug, Clone)] pub struct YYYYMMDDHHmmss; /// To serialize the date in Dateformats like YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY #[derive(Debug, Deserialize, Clone)] pub struct DateTime<T: TimeStrategy> { inner: PhantomData<T>, value: PrimitiveDateTime, } impl<T: TimeStrategy> From<PrimitiveDateTime> for DateTime<T> { fn from(value: PrimitiveDateTime) -> Self { Self { inner: PhantomData, value, } } } /// Time strategy for the Date, Eg: YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY pub trait TimeStrategy { /// Stringify the date as per the Time strategy fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result; } impl<T: TimeStrategy> Serialize for DateTime<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.collect_str(self) } } impl<T: TimeStrategy> std::fmt::Display for DateTime<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { T::fmt(&self.value, f) } } impl TimeStrategy for DDMMYYYY { fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let year = input.year(); #[allow(clippy::as_conversions)] let month = input.month() as u8; let day = input.day(); let output = format!("{day:02}{month:02}{year}"); f.write_str(&output) } } impl TimeStrategy for YYYYMMDD { fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let year = input.year(); #[allow(clippy::as_conversions)] let month: u8 = input.month() as u8; let day = input.day(); let output = format!("{year}{month:02}{day:02}"); f.write_str(&output) } } impl TimeStrategy for YYYYMMDDHHmmss { fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let year = input.year(); #[allow(clippy::as_conversions)] let month = input.month() as u8; let day = input.day(); let hour = input.hour(); let minute = input.minute(); let second = input.second(); let output = format!("{year}{month:02}{day:02}{hour:02}{minute:02}{second:02}"); f.write_str(&output) } } } /// Generate a nanoid with the given prefix and length #[inline] pub fn generate_id(length: usize, prefix: &str) -> String { format!("{}_{}", prefix, nanoid::nanoid!(length, &consts::ALPHABETS)) } /// Generate a ReferenceId with the default length with the given prefix fn generate_ref_id_with_default_length<const MAX_LENGTH: u8, const MIN_LENGTH: u8>( prefix: &str, ) -> id_type::LengthId<MAX_LENGTH, MIN_LENGTH> { id_type::LengthId::<MAX_LENGTH, MIN_LENGTH>::new(prefix) } /// Generate a customer id with default length, with prefix as `cus` pub fn generate_customer_id_of_default_length() -> id_type::CustomerId { use id_type::GenerateId; id_type::CustomerId::generate() } /// Generate a organization id with default length, with prefix as `org` pub fn generate_organization_id_of_default_length() -> id_type::OrganizationId { use id_type::GenerateId; id_type::OrganizationId::generate() } /// Generate a profile id with default length, with prefix as `pro` pub fn generate_profile_id_of_default_length() -> id_type::ProfileId { use id_type::GenerateId; id_type::ProfileId::generate() } /// Generate a routing id with default length, with prefix as `routing` pub fn generate_routing_id_of_default_length() -> id_type::RoutingId { use id_type::GenerateId; id_type::RoutingId::generate() } /// Generate a merchant_connector_account id with default length, with prefix as `mca` pub fn generate_merchant_connector_account_id_of_default_length( ) -> id_type::MerchantConnectorAccountId { use id_type::GenerateId; id_type::MerchantConnectorAccountId::generate() } /// Generate a profile_acquirer id with default length, with prefix as `mer_acq` pub fn generate_profile_acquirer_id_of_default_length() -> id_type::ProfileAcquirerId { use id_type::GenerateId; id_type::ProfileAcquirerId::generate() } /// Generate a nanoid with the given prefix and a default length #[inline] pub fn generate_id_with_default_len(prefix: &str) -> String { let len: usize = consts::ID_LENGTH; format!("{}_{}", prefix, nanoid::nanoid!(len, &consts::ALPHABETS)) } /// Generate a time-ordered (time-sortable) unique identifier using the current time #[inline] pub fn generate_time_ordered_id(prefix: &str) -> String { format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple()) } /// Generate a time-ordered (time-sortable) unique identifier using the current time without prefix #[inline] pub fn generate_time_ordered_id_without_prefix() -> String { uuid::Uuid::now_v7().as_simple().to_string() } /// Generate a nanoid with the specified length #[inline] pub fn generate_id_with_len(length: usize) -> String { nanoid::nanoid!(length, &consts::ALPHABETS) } #[allow(missing_docs)] pub trait DbConnectionParams { fn get_username(&self) -> &str; fn get_password(&self) -> Secret<String>; fn get_host(&self) -> &str; fn get_port(&self) -> u16; fn get_dbname(&self) -> &str; fn get_database_url(&self, schema: &str) -> String { format!( "postgres://{}:{}@{}:{}/{}?application_name={}&options=-c%20search_path%3D{}", self.get_username(), self.get_password().peek(), self.get_host(), self.get_port(), self.get_dbname(), schema, schema, ) } } // Can't add doc comments for macro invocations, neither does the macro allow it. #[allow(missing_docs)] mod base64_serializer { use base64_serde::base64_serde_type; base64_serde_type!(pub Base64Serializer, crate::consts::BASE64_ENGINE); } #[cfg(test)] mod nanoid_tests { #![allow(clippy::unwrap_used)] use super::*; use crate::{ consts::{ MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH, }, id_type::AlphaNumericId, }; #[test] fn test_generate_id_with_alphanumeric_id() { let alphanumeric_id = AlphaNumericId::from(generate_id(10, "def").into()); assert!(alphanumeric_id.is_ok()) } #[test] fn test_generate_merchant_ref_id_with_default_length() { let ref_id = id_type::LengthId::< MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH, >::from(generate_id_with_default_len("def").into()); assert!(ref_id.is_ok()) } } /// Module for tokenization-related functionality /// /// This module provides types and functions for handling tokenized payment data, /// including response structures and token generation utilities. #[cfg(all(feature = "v2", feature = "tokenization_v2"))] pub mod tokenization;
crates/common_utils/src/lib.rs
common_utils::src::lib
3,284
true
// File: crates/common_utils/src/new_type.rs // Module: common_utils::src::new_type //! Contains new types with restrictions use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH, pii::{Email, UpiVpaMaskingStrategy}, transformers::ForeignFrom, }; #[nutype::nutype( derive(Clone, Serialize, Deserialize, Debug), validate(len_char_min = 1, len_char_max = MAX_ALLOWED_MERCHANT_NAME_LENGTH) )] pub struct MerchantName(String); impl masking::SerializableSecret for MerchantName {} /// Function for masking alphanumeric characters in a string. /// /// # Arguments /// `val` /// - holds reference to the string to be masked. /// `unmasked_char_count` /// - minimum character count to remain unmasked for identification /// - this number is for keeping the characters unmasked from /// both beginning (if feasible) and ending of the string. /// `min_masked_char_count` /// - this ensures the minimum number of characters to be masked /// /// # Behaviour /// - Returns the original string if its length is less than or equal to `unmasked_char_count`. /// - If the string length allows, keeps `unmasked_char_count` characters unmasked at both start and end. /// - Otherwise, keeps `unmasked_char_count` characters unmasked only at the end. /// - Only alphanumeric characters are masked; other characters remain unchanged. /// /// # Examples /// Sort Code /// (12-34-56, 2, 2) -> 12-**-56 /// Routing number /// (026009593, 3, 3) -> 026***593 /// CNPJ /// (12345678901, 4, 4) -> *******8901 /// CNPJ /// (12345678901, 4, 3) -> 1234***8901 /// Pix key /// (123e-a452-1243-1244-000, 4, 4) -> 123e-****-****-****-000 /// IBAN /// (AL35202111090000000001234567, 5, 5) -> AL352******************34567 fn apply_mask(val: &str, unmasked_char_count: usize, min_masked_char_count: usize) -> String { let len = val.len(); if len <= unmasked_char_count { return val.to_string(); } let mask_start_index = // For showing only last `unmasked_char_count` characters if len < (unmasked_char_count * 2 + min_masked_char_count) { 0 // For showing first and last `unmasked_char_count` characters } else { unmasked_char_count }; let mask_end_index = len - unmasked_char_count - 1; let range = mask_start_index..=mask_end_index; val.chars() .enumerate() .fold(String::new(), |mut acc, (index, ch)| { if ch.is_alphanumeric() && range.contains(&index) { acc.push('*'); } else { acc.push(ch); } acc }) } /// Masked sort code #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedSortCode(Secret<String>); impl From<String> for MaskedSortCode { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 2, 2); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedSortCode { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked Routing number #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedRoutingNumber(Secret<String>); impl From<String> for MaskedRoutingNumber { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 3, 3); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedRoutingNumber { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked bank account #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedBankAccount(Secret<String>); impl From<String> for MaskedBankAccount { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 4, 4); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedBankAccount { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked IBAN #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedIban(Secret<String>); impl From<String> for MaskedIban { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 5, 5); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedIban { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked IBAN #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedBic(Secret<String>); impl From<String> for MaskedBic { fn from(src: String) -> Self { let masked_value = apply_mask(src.as_ref(), 3, 2); Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedBic { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } /// Masked UPI ID #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedUpiVpaId(Secret<String>); impl From<String> for MaskedUpiVpaId { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if let Some((user_identifier, bank_or_psp)) = src.split_once('@') { let masked_user_identifier = user_identifier .to_string() .chars() .take(unmasked_char_count) .collect::<String>() + &"*".repeat(user_identifier.len() - unmasked_char_count); format!("{masked_user_identifier}@{bank_or_psp}") } else { let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8); masked_value }; Self(Secret::from(masked_value)) } } impl From<Secret<String, UpiVpaMaskingStrategy>> for MaskedUpiVpaId { fn from(secret: Secret<String, UpiVpaMaskingStrategy>) -> Self { Self::from(secret.expose()) } } /// Masked Email #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedEmail(Secret<String>); impl From<String> for MaskedEmail { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if let Some((user_identifier, domain)) = src.split_once('@') { let masked_user_identifier = user_identifier .to_string() .chars() .take(unmasked_char_count) .collect::<String>() + &"*".repeat(user_identifier.len() - unmasked_char_count); format!("{masked_user_identifier}@{domain}") } else { let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8); masked_value }; Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedEmail { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } impl ForeignFrom<Email> for MaskedEmail { fn foreign_from(email: Email) -> Self { let email_value: String = email.expose().peek().to_owned(); Self::from(email_value) } } /// Masked Phone Number #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct MaskedPhoneNumber(Secret<String>); impl From<String> for MaskedPhoneNumber { fn from(src: String) -> Self { let unmasked_char_count = 2; let masked_value = if unmasked_char_count <= src.len() { let len = src.len(); // mask every character except the last 2 "*".repeat(len - unmasked_char_count).to_string() + src .get(len.saturating_sub(unmasked_char_count)..) .unwrap_or("") } else { src }; Self(Secret::from(masked_value)) } } impl From<Secret<String>> for MaskedPhoneNumber { fn from(secret: Secret<String>) -> Self { Self::from(secret.expose()) } } #[cfg(test)] mod apply_mask_fn_test { use masking::PeekInterface; use crate::new_type::{ apply_mask, MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }; #[test] fn test_masked_types() { let sort_code = MaskedSortCode::from("110011".to_string()); let routing_number = MaskedRoutingNumber::from("056008849".to_string()); let bank_account = MaskedBankAccount::from("12345678901234".to_string()); let iban = MaskedIban::from("NL02ABNA0123456789".to_string()); let upi_vpa = MaskedUpiVpaId::from("someusername@okhdfcbank".to_string()); // Standard masked data tests assert_eq!(sort_code.0.peek().to_owned(), "11**11".to_string()); assert_eq!(routing_number.0.peek().to_owned(), "056***849".to_string()); assert_eq!( bank_account.0.peek().to_owned(), "1234******1234".to_string() ); assert_eq!(iban.0.peek().to_owned(), "NL02A********56789".to_string()); assert_eq!( upi_vpa.0.peek().to_owned(), "so**********@okhdfcbank".to_string() ); } #[test] fn test_apply_mask_fn() { let value = "12345678901".to_string(); // Generic masked tests assert_eq!(apply_mask(&value, 2, 2), "12*******01".to_string()); assert_eq!(apply_mask(&value, 3, 2), "123*****901".to_string()); assert_eq!(apply_mask(&value, 3, 3), "123*****901".to_string()); assert_eq!(apply_mask(&value, 4, 3), "1234***8901".to_string()); assert_eq!(apply_mask(&value, 4, 4), "*******8901".to_string()); assert_eq!(apply_mask(&value, 5, 4), "******78901".to_string()); assert_eq!(apply_mask(&value, 5, 5), "******78901".to_string()); assert_eq!(apply_mask(&value, 6, 5), "*****678901".to_string()); assert_eq!(apply_mask(&value, 6, 6), "*****678901".to_string()); assert_eq!(apply_mask(&value, 7, 6), "****5678901".to_string()); assert_eq!(apply_mask(&value, 7, 7), "****5678901".to_string()); assert_eq!(apply_mask(&value, 8, 7), "***45678901".to_string()); assert_eq!(apply_mask(&value, 8, 8), "***45678901".to_string()); } }
crates/common_utils/src/new_type.rs
common_utils::src::new_type
2,820
true
// File: crates/common_utils/src/fp_utils.rs // Module: common_utils::src::fp_utils //! Functional programming utilities /// The Applicative trait provides a pure behavior, /// which can be used to create values of type f a from values of type a. pub trait Applicative<R> { /// The Associative type acts as a (f a) wrapper for Self. type WrappedSelf<T>; /// Applicative::pure(_) is abstraction with lifts any arbitrary type to underlying higher /// order type fn pure(v: R) -> Self::WrappedSelf<R>; } impl<R> Applicative<R> for Option<R> { type WrappedSelf<T> = Option<T>; fn pure(v: R) -> Self::WrappedSelf<R> { Some(v) } } impl<R, E> Applicative<R> for Result<R, E> { type WrappedSelf<T> = Result<T, E>; fn pure(v: R) -> Self::WrappedSelf<R> { Ok(v) } } /// This function wraps the evaluated result of `f` into current context, /// based on the condition provided into the `predicate` pub fn when<W: Applicative<(), WrappedSelf<()> = W>, F>(predicate: bool, f: F) -> W where F: FnOnce() -> W, { if predicate { f() } else { W::pure(()) } }
crates/common_utils/src/fp_utils.rs
common_utils::src::fp_utils
302
true
// File: crates/common_utils/src/signals.rs // Module: common_utils::src::signals //! Provide Interface for worker services to handle signals #[cfg(not(target_os = "windows"))] use futures::StreamExt; #[cfg(not(target_os = "windows"))] use router_env::logger; use tokio::sync::mpsc; /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received #[cfg(not(target_os = "windows"))] pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) { if let Some(signal) = sig.next().await { logger::info!( "Received signal: {:?}", signal_hook::low_level::signal_name(signal) ); match signal { signal_hook::consts::SIGTERM | signal_hook::consts::SIGINT => match sender.try_send(()) { Ok(_) => { logger::info!("Request for force shutdown received") } Err(_) => { logger::error!( "The receiver is closed, a termination call might already be sent" ) } }, _ => {} } } } /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received #[cfg(target_os = "windows")] pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {} /// This function is used to generate a list of signals that the signal_handler should listen for #[cfg(not(target_os = "windows"))] pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> { signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT]) } /// This function is used to generate a list of signals that the signal_handler should listen for #[cfg(target_os = "windows")] pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> { Ok(DummySignal) } /// Dummy Signal Handler for windows #[cfg(target_os = "windows")] #[derive(Debug, Clone)] pub struct DummySignal; #[cfg(target_os = "windows")] impl DummySignal { /// Dummy handler for signals in windows (empty) pub fn handle(&self) -> Self { self.clone() } /// Hollow implementation, for windows compatibility pub fn close(self) {} }
crates/common_utils/src/signals.rs
common_utils::src::signals
540
true
// File: crates/common_utils/src/access_token.rs // Module: common_utils::src::access_token //! Commonly used utilities for access token use std::fmt::Display; use crate::id_type; /// Create a key for fetching the access token from redis pub fn create_access_token_key( merchant_id: &id_type::MerchantId, merchant_connector_id_or_connector_name: impl Display, ) -> String { merchant_id.get_access_token_key(merchant_connector_id_or_connector_name) }
crates/common_utils/src/access_token.rs
common_utils::src::access_token
105
true
// File: crates/common_utils/src/metrics.rs // Module: common_utils::src::metrics //! Utilities for metrics pub mod utils;
crates/common_utils/src/metrics.rs
common_utils::src::metrics
30
true
// File: crates/common_utils/src/hashing.rs // Module: common_utils::src::hashing use masking::{PeekInterface, Secret, Strategy}; use serde::{Deserialize, Serialize, Serializer}; #[derive(Clone, PartialEq, Debug, Deserialize)] /// Represents a hashed string using blake3's hashing strategy. pub struct HashedString<T: Strategy<String>>(Secret<String, T>); impl<T: Strategy<String>> Serialize for HashedString<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let hashed_value = blake3::hash(self.0.peek().as_bytes()).to_hex(); hashed_value.serialize(serializer) } } impl<T: Strategy<String>> From<Secret<String, T>> for HashedString<T> { fn from(value: Secret<String, T>) -> Self { Self(value) } }
crates/common_utils/src/hashing.rs
common_utils::src::hashing
196
true
// File: crates/common_utils/src/validation.rs // Module: common_utils::src::validation //! Custom validations for some shared types. #![deny(clippy::invalid_regex)] use std::{collections::HashSet, sync::LazyLock}; use error_stack::report; use globset::Glob; use regex::Regex; #[cfg(feature = "logs")] use router_env::logger; use crate::errors::{CustomResult, ValidationError}; /// Validates a given phone number using the [phonenumber] crate /// /// It returns a [ValidationError::InvalidValue] in case it could not parse the phone number pub fn validate_phone_number(phone_number: &str) -> Result<(), ValidationError> { let _ = phonenumber::parse(None, phone_number).map_err(|e| ValidationError::InvalidValue { message: format!("Could not parse phone number: {phone_number}, because: {e:?}"), })?; Ok(()) } /// Performs a simple validation against a provided email address. pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> { #[deny(clippy::invalid_regex)] static EMAIL_REGEX: LazyLock<Option<Regex>> = LazyLock::new(|| { #[allow(unknown_lints)] #[allow(clippy::manual_ok_err)] match Regex::new( r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$", ) { Ok(regex) => Some(regex), Err(_error) => { #[cfg(feature = "logs")] logger::error!(?_error); None } } }); let email_regex = match EMAIL_REGEX.as_ref() { Some(regex) => Ok(regex), None => Err(report!(ValidationError::InvalidValue { message: "Invalid regex expression".into() })), }?; const EMAIL_MAX_LENGTH: usize = 319; if email.is_empty() || email.chars().count() > EMAIL_MAX_LENGTH { return Err(report!(ValidationError::InvalidValue { message: "Email address is either empty or exceeds maximum allowed length".into() })); } if !email_regex.is_match(email) { return Err(report!(ValidationError::InvalidValue { message: "Invalid email address format".into() })); } Ok(()) } /// Checks whether a given domain matches against a list of valid domain glob patterns pub fn validate_domain_against_allowed_domains( domain: &str, allowed_domains: HashSet<String>, ) -> bool { allowed_domains.iter().any(|allowed_domain| { Glob::new(allowed_domain) .map(|glob| glob.compile_matcher().is_match(domain)) .map_err(|err| { let err_msg = format!( "Invalid glob pattern for configured allowed_domain [{allowed_domain:?}]! - {err:?}", ); #[cfg(feature = "logs")] logger::error!(err_msg); err_msg }) .unwrap_or(false) }) } /// checks whether the input string contains potential XSS or SQL injection attack vectors pub fn contains_potential_xss_or_sqli(input: &str) -> bool { let decoded = urlencoding::decode(input).unwrap_or_else(|_| input.into()); // Check for suspicious percent-encoded patterns static PERCENT_ENCODED: LazyLock<Option<Regex>> = LazyLock::new(|| { Regex::new(r"%[0-9A-Fa-f]{2}") .map_err(|_err| { #[cfg(feature = "logs")] logger::error!(?_err); }) .ok() }); if decoded.contains('%') { match PERCENT_ENCODED.as_ref() { Some(regex) => { if regex.is_match(&decoded) { return true; } } None => return true, } } if ammonia::is_html(&decoded) { return true; } static XSS: LazyLock<Option<Regex>> = LazyLock::new(|| { Regex::new( r"(?is)\bon[a-z]+\s*=|\bjavascript\s*:|\bdata\s*:\s*text/html|\b(alert|prompt|confirm|eval)\s*\(", ) .map_err(|_err| { #[cfg(feature = "logs")] logger::error!(?_err); }) .ok() }); static SQLI: LazyLock<Option<Regex>> = LazyLock::new(|| { Regex::new( r"(?is)(?:')\s*or\s*'?\d+'?=?\d*|union\s+select|insert\s+into|drop\s+table|information_schema|sleep\s*\(|--|;", ) .map_err(|_err| { #[cfg(feature = "logs")] logger::error!(?_err); }) .ok() }); match XSS.as_ref() { Some(regex) => { if regex.is_match(&decoded) { return true; } } None => return true, } match SQLI.as_ref() { Some(regex) => { if regex.is_match(&decoded) { return true; } } None => return true, } false } #[cfg(test)] mod tests { use fake::{faker::internet::en::SafeEmail, Fake}; use proptest::{ prop_assert, strategy::{Just, NewTree, Strategy}, test_runner::TestRunner, }; use test_case::test_case; use super::*; #[derive(Debug)] struct ValidEmail; impl Strategy for ValidEmail { type Tree = Just<String>; type Value = String; fn new_tree(&self, _runner: &mut TestRunner) -> NewTree<Self> { Ok(Just(SafeEmail().fake())) } } #[test] fn test_validate_email() { let result = validate_email("[email protected]"); assert!(result.is_ok()); let result = validate_email("[email protected]"); assert!(result.is_ok()); let result = validate_email(""); assert!(result.is_err()); } #[test_case("+40745323456" ; "Romanian valid phone number")] #[test_case("+34912345678" ; "Spanish valid phone number")] #[test_case("+41 79 123 45 67" ; "Swiss valid phone number")] #[test_case("+66 81 234 5678" ; "Thailand valid phone number")] fn test_validate_phone_number(phone_number: &str) { assert!(validate_phone_number(phone_number).is_ok()); } #[test_case("9123456789" ; "Romanian invalid phone number")] fn test_invalid_phone_number(phone_number: &str) { let res = validate_phone_number(phone_number); assert!(res.is_err()); } proptest::proptest! { /// Example of unit test #[test] fn proptest_valid_fake_email(email in ValidEmail) { prop_assert!(validate_email(&email).is_ok()); } /// Example of unit test #[test] fn proptest_invalid_data_email(email in "\\PC*") { prop_assert!(validate_email(&email).is_err()); } #[test] fn proptest_invalid_email(email in "[.+]@(.+)") { prop_assert!(validate_email(&email).is_err()); } } #[test] fn detects_basic_script_tags() { assert!(contains_potential_xss_or_sqli( "<script>alert('xss')</script>" )); } #[test] fn detects_event_handlers() { assert!(contains_potential_xss_or_sqli( "onload=alert('xss') onclick=alert('xss') onmouseover=alert('xss')", )); } #[test] fn detects_data_url_payload() { assert!(contains_potential_xss_or_sqli( "data:text/html,<script>alert('xss')</script>", )); } #[test] fn detects_iframe_javascript_src() { assert!(contains_potential_xss_or_sqli( "<iframe src=javascript:alert('xss')></iframe>", )); } #[test] fn detects_svg_with_script() { assert!(contains_potential_xss_or_sqli( "<svg><script>alert('xss')</script></svg>", )); } #[test] fn detects_object_with_js() { assert!(contains_potential_xss_or_sqli( "<object data=javascript:alert('xss')></object>", )); } #[test] fn detects_mixed_case_tags() { assert!(contains_potential_xss_or_sqli( "<ScRiPt>alert('xss')</ScRiPt>" )); } #[test] fn detects_embedded_script_in_text() { assert!(contains_potential_xss_or_sqli( "Test<script>alert('xss')</script>Company", )); } #[test] fn detects_math_with_script() { assert!(contains_potential_xss_or_sqli( "<math><script>alert('xss')</script></math>", )); } #[test] fn detects_basic_sql_tautology() { assert!(contains_potential_xss_or_sqli("' OR '1'='1")); } #[test] fn detects_time_based_sqli() { assert!(contains_potential_xss_or_sqli("' OR SLEEP(5) --")); } #[test] fn detects_percent_encoded_sqli() { // %27 OR %271%27=%271 is a typical encoded variant assert!(contains_potential_xss_or_sqli("%27%20OR%20%271%27%3D%271")); } #[test] fn detects_benign_html_as_suspicious() { assert!(contains_potential_xss_or_sqli("<b>Hello</b>")); } #[test] fn allows_legitimate_plain_text() { assert!(!contains_potential_xss_or_sqli("My Test Company Ltd.")); } #[test] fn allows_normal_url() { assert!(!contains_potential_xss_or_sqli("https://example.com")); } #[test] fn allows_percent_char_without_encoding() { assert!(!contains_potential_xss_or_sqli("Get 50% off today")); } }
crates/common_utils/src/validation.rs
common_utils::src::validation
2,356
true
// File: crates/common_utils/src/pii.rs // Module: common_utils::src::pii //! Personal Identifiable Information protection. use std::{convert::AsRef, fmt, ops, str::FromStr}; use diesel::{ backend::Backend, deserialize, deserialize::FromSql, prelude::*, serialize::{Output, ToSql}, sql_types, AsExpression, }; use error_stack::ResultExt; use masking::{ExposeInterface, Secret, Strategy, WithType}; #[cfg(feature = "logs")] use router_env::logger; use serde::Deserialize; use crate::{ crypto::Encryptable, errors::{self, ValidationError}, validation::{validate_email, validate_phone_number}, }; /// A string constant representing a redacted or masked value. pub const REDACTED: &str = "Redacted"; /// Type alias for serde_json value which has Secret Information pub type SecretSerdeValue = Secret<serde_json::Value>; /// Strategy for masking a PhoneNumber #[derive(Debug)] pub enum PhoneNumberStrategy {} /// Phone Number #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(try_from = "String")] pub struct PhoneNumber(Secret<String, PhoneNumberStrategy>); impl<T> Strategy<T> for PhoneNumberStrategy where T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); if let Some(val_str) = val_str.get(val_str.len() - 4..) { // masks everything but the last 4 digits write!(f, "{}{}", "*".repeat(val_str.len() - 4), val_str) } else { #[cfg(feature = "logs")] logger::error!("Invalid phone number: {val_str}"); WithType::fmt(val, f) } } } impl FromStr for PhoneNumber { type Err = error_stack::Report<ValidationError>; fn from_str(phone_number: &str) -> Result<Self, Self::Err> { validate_phone_number(phone_number)?; let secret = Secret::<String, PhoneNumberStrategy>::new(phone_number.to_string()); Ok(Self(secret)) } } impl TryFrom<String> for PhoneNumber { type Error = error_stack::Report<errors::ParsingError>; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value).change_context(errors::ParsingError::PhoneNumberParsingError) } } impl ops::Deref for PhoneNumber { type Target = Secret<String, PhoneNumberStrategy>; fn deref(&self) -> &Self::Target { &self.0 } } impl ops::DerefMut for PhoneNumber { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<DB> Queryable<sql_types::Text, DB> for PhoneNumber where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for PhoneNumber where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self::from_str(val.as_str())?) } } impl<DB> ToSql<sql_types::Text, DB> for PhoneNumber where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } /* /// Phone number #[derive(Debug)] pub struct PhoneNumber; impl<T> Strategy<T> for PhoneNumber where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); if val_str.len() < 10 || val_str.len() > 12 { return WithType::fmt(val, f); } write!( f, "{}{}{}", &val_str[..2], "*".repeat(val_str.len() - 5), &val_str[(val_str.len() - 3)..] ) } } */ /// Strategy for Encryption #[derive(Debug)] pub enum EncryptionStrategy {} impl<T> Strategy<T> for EncryptionStrategy where T: AsRef<[u8]>, { fn fmt(value: &T, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( fmt, "*** Encrypted data of length {} bytes ***", value.as_ref().len() ) } } /// Client secret #[derive(Debug)] pub enum ClientSecret {} impl<T> Strategy<T> for ClientSecret where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); let client_secret_segments: Vec<&str> = val_str.split('_').collect(); if client_secret_segments.len() != 4 || !client_secret_segments.contains(&"pay") || !client_secret_segments.contains(&"secret") { return WithType::fmt(val, f); } if let Some((client_secret_segments_0, client_secret_segments_1)) = client_secret_segments .first() .zip(client_secret_segments.get(1)) { write!( f, "{}_{}_{}", client_secret_segments_0, client_secret_segments_1, "*".repeat( val_str.len() - (client_secret_segments_0.len() + client_secret_segments_1.len() + 2) ) ) } else { #[cfg(feature = "logs")] logger::error!("Invalid client secret: {val_str}"); WithType::fmt(val, f) } } } /// Strategy for masking Email #[derive(Debug, Copy, Clone, Deserialize)] pub enum EmailStrategy {} impl<T> Strategy<T> for EmailStrategy where T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); match val_str.split_once('@') { Some((a, b)) => write!(f, "{}@{}", "*".repeat(a.len()), b), None => WithType::fmt(val, f), } } } /// Email address #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default, AsExpression, )] #[diesel(sql_type = sql_types::Text)] #[serde(try_from = "String")] pub struct Email(Secret<String, EmailStrategy>); impl From<Encryptable<Secret<String, EmailStrategy>>> for Email { fn from(item: Encryptable<Secret<String, EmailStrategy>>) -> Self { Self(item.into_inner()) } } impl ExposeInterface<Secret<String, EmailStrategy>> for Email { fn expose(self) -> Secret<String, EmailStrategy> { self.0 } } impl TryFrom<String> for Email { type Error = error_stack::Report<errors::ParsingError>; fn try_from(value: String) -> Result<Self, Self::Error> { Self::from_str(&value).change_context(errors::ParsingError::EmailParsingError) } } impl ops::Deref for Email { type Target = Secret<String, EmailStrategy>; fn deref(&self) -> &Self::Target { &self.0 } } impl ops::DerefMut for Email { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<DB> Queryable<sql_types::Text, DB> for Email where DB: Backend, Self: FromSql<sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> deserialize::Result<Self> { Ok(row) } } impl<DB> FromSql<sql_types::Text, DB> for Email where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let val = String::from_sql(bytes)?; Ok(Self::from_str(val.as_str())?) } } impl<DB> ToSql<sql_types::Text, DB> for Email where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl FromStr for Email { type Err = error_stack::Report<ValidationError>; fn from_str(email: &str) -> Result<Self, Self::Err> { if email.eq(REDACTED) { return Ok(Self(Secret::new(email.to_string()))); } match validate_email(email) { Ok(_) => { let secret = Secret::<String, EmailStrategy>::new(email.to_string()); Ok(Self(secret)) } Err(_) => Err(ValidationError::InvalidValue { message: "Invalid email address format".into(), } .into()), } } } /// IP address #[derive(Debug)] pub enum IpAddress {} impl<T> Strategy<T> for IpAddress where T: AsRef<str>, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); let segments: Vec<&str> = val_str.split('.').collect(); if segments.len() != 4 { return WithType::fmt(val, f); } for seg in segments.iter() { if seg.is_empty() || seg.len() > 3 { return WithType::fmt(val, f); } } if let Some(segments) = segments.first() { write!(f, "{segments}.**.**.**") } else { #[cfg(feature = "logs")] logger::error!("Invalid IP address: {val_str}"); WithType::fmt(val, f) } } } /// Strategy for masking UPI VPA's #[derive(Debug)] pub enum UpiVpaMaskingStrategy {} impl<T> Strategy<T> for UpiVpaMaskingStrategy where T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let vpa_str: &str = val.as_ref(); if let Some((user_identifier, bank_or_psp)) = vpa_str.split_once('@') { let masked_user_identifier = "*".repeat(user_identifier.len()); write!(f, "{masked_user_identifier}@{bank_or_psp}") } else { WithType::fmt(val, f) } } } #[cfg(test)] mod pii_masking_strategy_tests { use std::str::FromStr; use masking::{ExposeInterface, Secret}; use super::{ClientSecret, Email, IpAddress, UpiVpaMaskingStrategy}; use crate::pii::{EmailStrategy, REDACTED}; /* #[test] fn test_valid_phone_number_masking() { let secret: Secret<String, PhoneNumber> = Secret::new("9123456789".to_string()); assert_eq!("99*****299", format!("{}", secret)); } #[test] fn test_invalid_phone_number_masking() { let secret: Secret<String, PhoneNumber> = Secret::new("99229922".to_string()); assert_eq!("*** alloc::string::String ***", format!("{}", secret)); let secret: Secret<String, PhoneNumber> = Secret::new("9922992299229922".to_string()); assert_eq!("*** alloc::string::String ***", format!("{}", secret)); } */ #[test] fn test_valid_email_masking() { let secret: Secret<String, EmailStrategy> = Secret::new("[email protected]".to_string()); assert_eq!("*******@test.com", format!("{secret:?}")); let secret: Secret<String, EmailStrategy> = Secret::new("[email protected]".to_string()); assert_eq!("********@gmail.com", format!("{secret:?}")); } #[test] fn test_invalid_email_masking() { let secret: Secret<String, EmailStrategy> = Secret::new("myemailgmail.com".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); let secret: Secret<String, EmailStrategy> = Secret::new("myemail$gmail.com".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_newtype_email() { let email_check = Email::from_str("[email protected]"); assert!(email_check.is_ok()); } #[test] fn test_invalid_newtype_email() { let email_check = Email::from_str("example@abc@com"); assert!(email_check.is_err()); } #[test] fn test_redacted_email() { let email_result = Email::from_str(REDACTED); assert!(email_result.is_ok()); if let Ok(email) = email_result { let secret_value = email.0.expose(); assert_eq!(secret_value.as_str(), REDACTED); } } #[test] fn test_valid_ip_addr_masking() { let secret: Secret<String, IpAddress> = Secret::new("123.23.1.78".to_string()); assert_eq!("123.**.**.**", format!("{secret:?}")); } #[test] fn test_invalid_ip_addr_masking() { let secret: Secret<String, IpAddress> = Secret::new("123.4.56".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); let secret: Secret<String, IpAddress> = Secret::new("123.4567.12.4".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); let secret: Secret<String, IpAddress> = Secret::new("123..4.56".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_client_secret_masking() { let secret: Secret<String, ClientSecret> = Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret_tLjTz9tAQxUVEFqfmOIP".to_string()); assert_eq!( "pay_uszFB2QGe9MmLY65ojhT_***************************", format!("{secret:?}") ); } #[test] fn test_invalid_client_secret_masking() { let secret: Secret<String, IpAddress> = Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_phone_number_default_masking() { let secret: Secret<String> = Secret::new("+40712345678".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } #[test] fn test_valid_upi_vpa_masking() { let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name@upi".to_string()); assert_eq!("*******@upi", format!("{secret:?}")); } #[test] fn test_invalid_upi_vpa_masking() { let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name_upi".to_string()); assert_eq!("*** alloc::string::String ***", format!("{secret:?}")); } }
crates/common_utils/src/pii.rs
common_utils::src::pii
3,631
true
// File: crates/common_utils/src/errors.rs // Module: common_utils::src::errors //! Errors and error specific types for universal use use serde::Serialize; use crate::types::MinorUnit; /// Custom Result /// A custom datatype that wraps the error variant <E> into a report, allowing /// error_stack::Report<E> specific extendability /// /// Effectively, equivalent to `Result<T, error_stack::Report<E>>` pub type CustomResult<T, E> = error_stack::Result<T, E>; /// Parsing Errors #[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented #[derive(Debug, thiserror::Error)] pub enum ParsingError { ///Failed to parse enum #[error("Failed to parse enum: {0}")] EnumParseFailure(&'static str), ///Failed to parse struct #[error("Failed to parse struct: {0}")] StructParseFailure(&'static str), /// Failed to encode data to given format #[error("Failed to serialize to {0} format")] EncodeError(&'static str), /// Failed to parse data #[error("Unknown error while parsing")] UnknownError, /// Failed to parse datetime #[error("Failed to parse datetime")] DateTimeParsingError, /// Failed to parse email #[error("Failed to parse email")] EmailParsingError, /// Failed to parse phone number #[error("Failed to parse phone number")] PhoneNumberParsingError, /// Failed to parse Float value for converting to decimal points #[error("Failed to parse Float value for converting to decimal points")] FloatToDecimalConversionFailure, /// Failed to parse Decimal value for i64 value conversion #[error("Failed to parse Decimal value for i64 value conversion")] DecimalToI64ConversionFailure, /// Failed to parse string value for f64 value conversion #[error("Failed to parse string value for f64 value conversion")] StringToFloatConversionFailure, /// Failed to parse i64 value for f64 value conversion #[error("Failed to parse i64 value for f64 value conversion")] I64ToDecimalConversionFailure, /// Failed to parse i64 value for String value conversion #[error("Failed to parse i64 value for String value conversion")] I64ToStringConversionFailure, /// Failed to parse String value to Decimal value conversion because `error` #[error("Failed to parse String value to Decimal value conversion because {error}")] StringToDecimalConversionFailure { error: String }, /// Failed to convert the given integer because of integer overflow error #[error("Integer Overflow error")] IntegerOverflow, /// Failed to parse url #[error("Failed to parse url")] UrlParsingError, } /// Validation errors. #[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum ValidationError { /// The provided input is missing a required field. #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: String }, /// An incorrect value was provided for the field specified by `field_name`. #[error("Incorrect value provided for field: {field_name}")] IncorrectValueProvided { field_name: &'static str }, /// An invalid input was provided. #[error("{message}")] InvalidValue { message: String }, } /// Integrity check errors. #[derive(Debug, Clone, PartialEq, Default, Serialize)] pub struct IntegrityCheckError { /// Field names for which integrity check failed! pub field_names: String, /// Connector transaction reference id pub connector_transaction_id: Option<String>, } /// Cryptographic algorithm errors #[derive(Debug, thiserror::Error)] pub enum CryptoError { /// The cryptographic algorithm was unable to encode the message #[error("Failed to encode given message")] EncodingFailed, /// The cryptographic algorithm was unable to decode the message #[error("Failed to decode given message")] DecodingFailed, /// The cryptographic algorithm was unable to sign the message #[error("Failed to sign message")] MessageSigningFailed, /// The cryptographic algorithm was unable to verify the given signature #[error("Failed to verify signature")] SignatureVerificationFailed, /// The provided key length is invalid for the cryptographic algorithm #[error("Invalid key length")] InvalidKeyLength, /// The provided IV length is invalid for the cryptographic algorithm #[error("Invalid IV length")] InvalidIvLength, /// The provided authentication tag length is invalid for the cryptographic algorithm #[error("Invalid authentication tag length")] InvalidTagLength, } /// Errors for Qr code handling #[derive(Debug, thiserror::Error)] pub enum QrCodeError { /// Failed to encode data into Qr code #[error("Failed to create Qr code")] FailedToCreateQrCode, /// Failed to parse hex color #[error("Invalid hex color code supplied")] InvalidHexColor, } /// Api Models construction error #[derive(Debug, Clone, thiserror::Error, PartialEq)] pub enum PercentageError { /// Percentage Value provided was invalid #[error("Invalid Percentage value")] InvalidPercentageValue, /// Error occurred while calculating percentage #[error("Failed apply percentage of {percentage} on {amount}")] UnableToApplyPercentage { /// percentage value percentage: f32, /// amount value amount: MinorUnit, }, } /// Allows [error_stack::Report] to change between error contexts /// using the dependent [ErrorSwitch] trait to define relations & mappings between traits pub trait ReportSwitchExt<T, U> { /// Switch to the intended report by calling switch /// requires error switch to be already implemented on the error type fn switch(self) -> Result<T, error_stack::Report<U>>; } impl<T, U, V> ReportSwitchExt<T, U> for Result<T, error_stack::Report<V>> where V: ErrorSwitch<U> + error_stack::Context, U: error_stack::Context, { #[track_caller] fn switch(self) -> Result<T, error_stack::Report<U>> { match self { Ok(i) => Ok(i), Err(er) => { let new_c = er.current_context().switch(); Err(er.change_context(new_c)) } } } } #[allow(missing_docs)] #[derive(Debug, thiserror::Error)] pub enum KeyManagerClientError { #[error("Failed to construct header from the given value")] FailedtoConstructHeader, #[error("Failed to send request to Keymanager")] RequestNotSent(String), #[error("URL encoding of request failed")] UrlEncodingFailed, #[error("Failed to build the reqwest client ")] ClientConstructionFailed, #[error("Failed to send the request to Keymanager")] RequestSendFailed, #[error("Internal Server Error Received {0:?}")] InternalServerError(bytes::Bytes), #[error("Bad request received {0:?}")] BadRequest(bytes::Bytes), #[error("Unexpected Error occurred while calling the KeyManager")] Unexpected(bytes::Bytes), #[error("Response Decoding failed")] ResponseDecodingFailed, } #[allow(missing_docs)] #[derive(Debug, thiserror::Error)] pub enum KeyManagerError { #[error("Failed to add key to the KeyManager")] KeyAddFailed, #[error("Failed to transfer the key to the KeyManager")] KeyTransferFailed, #[error("Failed to Encrypt the data in the KeyManager")] EncryptionFailed, #[error("Failed to Decrypt the data in the KeyManager")] DecryptionFailed, } /// Allow [error_stack::Report] to convert between error types /// This auto-implements [ReportSwitchExt] for the corresponding errors pub trait ErrorSwitch<T> { /// Get the next error type that the source error can be escalated into /// This does not consume the source error since we need to keep it in context fn switch(&self) -> T; } /// Allow [error_stack::Report] to convert between error types /// This serves as an alternative to [ErrorSwitch] pub trait ErrorSwitchFrom<T> { /// Convert to an error type that the source can be escalated into /// This does not consume the source error since we need to keep it in context fn switch_from(error: &T) -> Self; } impl<T, S> ErrorSwitch<T> for S where T: ErrorSwitchFrom<Self>, { fn switch(&self) -> T { T::switch_from(self) } }
crates/common_utils/src/errors.rs
common_utils::src::errors
1,857
true
// File: crates/common_utils/src/keymanager.rs // Module: common_utils::src::keymanager //! Consists of all the common functions to use the Keymanager. use core::fmt::Debug; use std::str::FromStr; use base64::Engine; use error_stack::ResultExt; use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; use masking::{PeekInterface, StrongSecret}; use once_cell::sync::OnceCell; use router_env::{instrument, logger, tracing}; use crate::{ consts::{BASE64_ENGINE, TENANT_HEADER}, errors, types::keymanager::{ BatchDecryptDataRequest, DataKeyCreateResponse, DecryptDataRequest, EncryptionCreateRequest, EncryptionTransferRequest, GetKeymanagerTenant, KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest, }, }; const CONTENT_TYPE: &str = "Content-Type"; static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); static DEFAULT_ENCRYPTION_VERSION: &str = "v1"; #[cfg(feature = "km_forward_x_request_id")] const X_REQUEST_ID: &str = "X-Request-Id"; /// Get keymanager client constructed from the url and state #[instrument(skip_all)] #[allow(unused_mut)] fn get_api_encryption_client( state: &KeyManagerState, ) -> errors::CustomResult<reqwest::Client, errors::KeyManagerClientError> { let get_client = || { let mut client = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .pool_idle_timeout(std::time::Duration::from_secs( state.client_idle_timeout.unwrap_or_default(), )); #[cfg(feature = "keymanager_mtls")] { let cert = state.cert.clone(); let ca = state.ca.clone(); let identity = reqwest::Identity::from_pem(cert.peek().as_ref()) .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; let ca_cert = reqwest::Certificate::from_pem(ca.peek().as_ref()) .change_context(errors::KeyManagerClientError::ClientConstructionFailed)?; client = client .use_rustls_tls() .identity(identity) .add_root_certificate(ca_cert) .https_only(true); } client .build() .change_context(errors::KeyManagerClientError::ClientConstructionFailed) }; Ok(ENCRYPTION_API_CLIENT.get_or_try_init(get_client)?.clone()) } /// Generic function to send the request to keymanager #[instrument(skip_all)] pub async fn send_encryption_request<T>( state: &KeyManagerState, headers: HeaderMap, url: String, method: Method, request_body: T, ) -> errors::CustomResult<reqwest::Response, errors::KeyManagerClientError> where T: ConvertRaw, { let client = get_api_encryption_client(state)?; let url = reqwest::Url::parse(&url) .change_context(errors::KeyManagerClientError::UrlEncodingFailed)?; client .request(method, url) .json(&ConvertRaw::convert_raw(request_body)?) .headers(headers) .send() .await .change_context(errors::KeyManagerClientError::RequestNotSent( "Unable to send request to encryption service".to_string(), )) } /// Generic function to call the Keymanager and parse the response back #[instrument(skip_all)] pub async fn call_encryption_service<T, R>( state: &KeyManagerState, method: Method, endpoint: &str, request_body: T, ) -> errors::CustomResult<R, errors::KeyManagerClientError> where T: GetKeymanagerTenant + ConvertRaw + Send + Sync + 'static + Debug, R: serde::de::DeserializeOwned, { let url = format!("{}/{endpoint}", &state.url); logger::info!(key_manager_request=?request_body); let mut header = vec![]; header.push(( HeaderName::from_str(CONTENT_TYPE) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, HeaderValue::from_str("application/json") .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, )); #[cfg(feature = "km_forward_x_request_id")] if let Some(request_id) = state.request_id { header.push(( HeaderName::from_str(X_REQUEST_ID) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, HeaderValue::from_str(request_id.as_hyphenated().to_string().as_str()) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, )) } //Add Tenant ID header.push(( HeaderName::from_str(TENANT_HEADER) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, HeaderValue::from_str(request_body.get_tenant_id(state).get_string_repr()) .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, )); let response = send_encryption_request( state, HeaderMap::from_iter(header.into_iter()), url, method, request_body, ) .await .map_err(|err| err.change_context(errors::KeyManagerClientError::RequestSendFailed))?; logger::info!(key_manager_response=?response); match response.status() { StatusCode::OK => response .json::<R>() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed), StatusCode::INTERNAL_SERVER_ERROR => { Err(errors::KeyManagerClientError::InternalServerError( response .bytes() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, ) .into()) } StatusCode::BAD_REQUEST => Err(errors::KeyManagerClientError::BadRequest( response .bytes() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, ) .into()), _ => Err(errors::KeyManagerClientError::Unexpected( response .bytes() .await .change_context(errors::KeyManagerClientError::ResponseDecodingFailed)?, ) .into()), } } /// Trait to convert the raw data to the required format for encryption service request pub trait ConvertRaw { /// Return type of the convert_raw function type Output: serde::Serialize; /// Function to convert the raw data to the required format for encryption service request fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError>; } impl<T: serde::Serialize> ConvertRaw for T { type Output = T; fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { Ok(self) } } impl ConvertRaw for TransientDecryptDataRequest { type Output = DecryptDataRequest; fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { let data = match String::from_utf8(self.data.peek().clone()) { Ok(data) => data, Err(_) => { let data = BASE64_ENGINE.encode(self.data.peek().clone()); format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") } }; Ok(DecryptDataRequest { identifier: self.identifier, data: StrongSecret::new(data), }) } } impl ConvertRaw for TransientBatchDecryptDataRequest { type Output = BatchDecryptDataRequest; fn convert_raw(self) -> Result<Self::Output, errors::KeyManagerClientError> { let data = self .data .iter() .map(|(k, v)| { let value = match String::from_utf8(v.peek().clone()) { Ok(data) => data, Err(_) => { let data = BASE64_ENGINE.encode(v.peek().clone()); format!("{DEFAULT_ENCRYPTION_VERSION}:{data}") } }; (k.to_owned(), StrongSecret::new(value)) }) .collect(); Ok(BatchDecryptDataRequest { data, identifier: self.identifier, }) } } /// A function to create the key in keymanager #[instrument(skip_all)] pub async fn create_key_in_key_manager( state: &KeyManagerState, request_body: EncryptionCreateRequest, ) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { call_encryption_service(state, Method::POST, "key/create", request_body) .await .change_context(errors::KeyManagerError::KeyAddFailed) } /// A function to transfer the key in keymanager #[instrument(skip_all)] pub async fn transfer_key_to_key_manager( state: &KeyManagerState, request_body: EncryptionTransferRequest, ) -> errors::CustomResult<DataKeyCreateResponse, errors::KeyManagerError> { call_encryption_service(state, Method::POST, "key/transfer", request_body) .await .change_context(errors::KeyManagerError::KeyTransferFailed) }
crates/common_utils/src/keymanager.rs
common_utils::src::keymanager
1,962
true
// File: crates/common_utils/src/ucs_types.rs // Module: common_utils::src::ucs_types use crate::id_type; /// Represents a reference ID for the Unified Connector Service (UCS). /// /// This enum can hold either a payment reference ID or a refund reference ID, /// allowing for a unified way to handle different types of transaction references /// when interacting with the UCS. #[derive(Debug)] pub enum UcsReferenceId { /// A payment reference ID. /// /// This variant wraps a [`PaymentReferenceId`](id_type::PaymentReferenceId) /// and is used to identify a payment transaction within the UCS. Payment(id_type::PaymentReferenceId), /// A refund reference ID. /// /// This variant wraps a [`RefundReferenceId`](id_type::RefundReferenceId) /// and is used to identify a refund transaction within the UCS. Refund(id_type::RefundReferenceId), } impl UcsReferenceId { /// Returns the string representation of the reference ID. /// /// This method matches the enum variant and calls the `get_string_repr` /// method of the underlying ID type (either `PaymentReferenceId` or `RefundReferenceId`) /// to get its string representation. /// /// # Returns /// /// A string slice (`&str`) representing the reference ID. pub fn get_string_repr(&self) -> &str { match self { Self::Payment(id) => id.get_string_repr(), Self::Refund(id) => id.get_string_repr(), } } }
crates/common_utils/src/ucs_types.rs
common_utils::src::ucs_types
332
true
// File: crates/common_utils/src/id_type.rs // Module: common_utils::src::id_type //! Common ID types //! The id type can be used to create specific id types with custom behaviour mod api_key; mod authentication; mod client_secret; mod customer; #[cfg(feature = "v2")] mod global_id; mod invoice; mod merchant; mod merchant_connector_account; mod organization; mod payment; mod payout; mod profile; mod profile_acquirer; mod refunds; mod relay; mod routing; mod subscription; mod tenant; mod webhook_endpoint; use std::{borrow::Cow, fmt::Debug}; use diesel::{ backend::Backend, deserialize::FromSql, expression::AsExpression, serialize::{Output, ToSql}, sql_types, }; pub use payout::PayoutId; use serde::{Deserialize, Serialize}; use thiserror::Error; #[cfg(feature = "v2")] pub use self::global_id::{ customer::GlobalCustomerId, payment::{GlobalAttemptId, GlobalPaymentId}, payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId}, refunds::GlobalRefundId, token::GlobalTokenId, CellId, }; pub use self::{ api_key::ApiKeyId, authentication::AuthenticationId, client_secret::ClientSecretId, customer::CustomerId, invoice::InvoiceId, merchant::MerchantId, merchant_connector_account::MerchantConnectorAccountId, organization::OrganizationId, payment::{PaymentId, PaymentReferenceId}, profile::ProfileId, profile_acquirer::ProfileAcquirerId, refunds::RefundReferenceId, relay::RelayId, routing::RoutingId, subscription::SubscriptionId, tenant::TenantId, webhook_endpoint::WebhookEndpointId, }; use crate::{fp_utils::when, generate_id_with_default_len}; #[inline] fn is_valid_id_character(input_char: char) -> bool { input_char.is_ascii_alphanumeric() || matches!(input_char, '_' | '-') } /// This functions checks for the input string to contain valid characters /// Returns Some(char) if there are any invalid characters, else None fn get_invalid_input_character(input_string: Cow<'static, str>) -> Option<char> { input_string .trim() .chars() .find(|&char| !is_valid_id_character(char)) } #[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)] /// A type for alphanumeric ids pub(crate) struct AlphaNumericId(String); #[derive(Debug, Deserialize, Hash, Serialize, Error, Eq, PartialEq)] #[error("value `{0}` contains invalid character `{1}`")] /// The error type for alphanumeric id pub(crate) struct AlphaNumericIdError(String, char); impl<'de> Deserialize<'de> for AlphaNumericId { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from(deserialized_string.into()).map_err(serde::de::Error::custom) } } impl AlphaNumericId { /// Creates a new alphanumeric id from string by applying validation checks pub fn from(input_string: Cow<'static, str>) -> Result<Self, AlphaNumericIdError> { let invalid_character = get_invalid_input_character(input_string.clone()); if let Some(invalid_character) = invalid_character { Err(AlphaNumericIdError( input_string.to_string(), invalid_character, ))? } Ok(Self(input_string.to_string())) } /// Create a new alphanumeric id without any validations pub(crate) fn new_unchecked(input_string: String) -> Self { Self(input_string) } /// Generate a new alphanumeric id of default length pub(crate) fn new(prefix: &str) -> Self { Self(generate_id_with_default_len(prefix)) } } /// A common type of id that can be used for reference ids with length constraint #[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub(crate) struct LengthId<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(AlphaNumericId); /// Error generated from violation of constraints for MerchantReferenceId #[derive(Debug, Error, PartialEq, Eq)] pub(crate) enum LengthIdError { #[error("the maximum allowed length for this field is {0}")] /// Maximum length of string violated MaxLengthViolated(u8), #[error("the minimum required length for this field is {0}")] /// Minimum length of string violated MinLengthViolated(u8), #[error("{0}")] /// Input contains invalid characters AlphanumericIdError(AlphaNumericIdError), } impl From<AlphaNumericIdError> for LengthIdError { fn from(alphanumeric_id_error: AlphaNumericIdError) -> Self { Self::AlphanumericIdError(alphanumeric_id_error) } } impl<const MAX_LENGTH: u8, const MIN_LENGTH: u8> LengthId<MAX_LENGTH, MIN_LENGTH> { /// Generates new [MerchantReferenceId] from the given input string pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthIdError> { let trimmed_input_string = input_string.trim().to_string(); let length_of_input_string = u8::try_from(trimmed_input_string.len()) .map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?; when(length_of_input_string > MAX_LENGTH, || { Err(LengthIdError::MaxLengthViolated(MAX_LENGTH)) })?; when(length_of_input_string < MIN_LENGTH, || { Err(LengthIdError::MinLengthViolated(MIN_LENGTH)) })?; let alphanumeric_id = match AlphaNumericId::from(trimmed_input_string.into()) { Ok(valid_alphanumeric_id) => valid_alphanumeric_id, Err(error) => Err(LengthIdError::AlphanumericIdError(error))?, }; Ok(Self(alphanumeric_id)) } /// Generate a new MerchantRefId of default length with the given prefix pub fn new(prefix: &str) -> Self { Self(AlphaNumericId::new(prefix)) } /// Use this function only if you are sure that the length is within the range pub(crate) fn new_unchecked(alphanumeric_id: AlphaNumericId) -> Self { Self(alphanumeric_id) } #[cfg(feature = "v2")] /// Create a new LengthId from aplhanumeric id pub(crate) fn from_alphanumeric_id( alphanumeric_id: AlphaNumericId, ) -> Result<Self, LengthIdError> { let length_of_input_string = alphanumeric_id.0.len(); let length_of_input_string = u8::try_from(length_of_input_string) .map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?; when(length_of_input_string > MAX_LENGTH, || { Err(LengthIdError::MaxLengthViolated(MAX_LENGTH)) })?; when(length_of_input_string < MIN_LENGTH, || { Err(LengthIdError::MinLengthViolated(MIN_LENGTH)) })?; Ok(Self(alphanumeric_id)) } } impl<'de, const MAX_LENGTH: u8, const MIN_LENGTH: u8> Deserialize<'de> for LengthId<MAX_LENGTH, MIN_LENGTH> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from(deserialized_string.into()).map_err(serde::de::Error::custom) } } impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> ToSql<sql_types::Text, DB> for LengthId<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0 .0.to_sql(out) } } impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> FromSql<sql_types::Text, DB> for LengthId<MAX_LENGTH, MIN_LENGTH> where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let string_val = String::from_sql(value)?; Ok(Self(AlphaNumericId::new_unchecked(string_val))) } } /// An interface to generate object identifiers. pub trait GenerateId { /// Generates a random object identifier. fn generate() -> Self; } #[cfg(test)] mod alphanumeric_id_tests { #![allow(clippy::unwrap_used)] use super::*; const VALID_UNDERSCORE_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#; const EXPECTED_VALID_UNDERSCORE_ID: &str = "cus_abcdefghijklmnopqrstuv"; const VALID_HYPHEN_ID_JSON: &str = r#""cus-abcdefghijklmnopqrstuv""#; const VALID_HYPHEN_ID_STRING: &str = "cus-abcdefghijklmnopqrstuv"; const INVALID_ID_WITH_SPACES: &str = r#""cus abcdefghijklmnopqrstuv""#; const INVALID_ID_WITH_EMOJIS: &str = r#""cus_abc🦀""#; #[test] fn test_id_deserialize_underscore() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(VALID_UNDERSCORE_ID_JSON); let alphanumeric_id = AlphaNumericId::from(EXPECTED_VALID_UNDERSCORE_ID.into()).unwrap(); assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id); } #[test] fn test_id_deserialize_hyphen() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(VALID_HYPHEN_ID_JSON); let alphanumeric_id = AlphaNumericId::from(VALID_HYPHEN_ID_STRING.into()).unwrap(); assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id); } #[test] fn test_id_deserialize_with_spaces() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_SPACES); assert!(parsed_alphanumeric_id.is_err()); } #[test] fn test_id_deserialize_with_emojis() { let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_EMOJIS); assert!(parsed_alphanumeric_id.is_err()); } } #[cfg(test)] mod merchant_reference_id_tests { use super::*; const VALID_REF_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#; const MAX_LENGTH: u8 = 36; const MIN_LENGTH: u8 = 6; const INVALID_REF_ID_JSON: &str = r#""cus abcdefghijklmnopqrstuv""#; const INVALID_REF_ID_LENGTH: &str = r#""cus_abcdefghijklmnopqrstuvwxyzabcdefghij""#; #[test] fn test_valid_reference_id() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(VALID_REF_ID_JSON); dbg!(&parsed_merchant_reference_id); assert!(parsed_merchant_reference_id.is_ok()); } #[test] fn test_invalid_ref_id() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON); assert!(parsed_merchant_reference_id.is_err()); } #[test] fn test_invalid_ref_id_error_message() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON); let expected_error_message = r#"value `cus abcdefghijklmnopqrstuv` contains invalid character ` `"#.to_string(); let error_message = parsed_merchant_reference_id .err() .map(|error| error.to_string()); assert_eq!(error_message, Some(expected_error_message)); } #[test] fn test_invalid_ref_id_length() { let parsed_merchant_reference_id = serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_LENGTH); dbg!(&parsed_merchant_reference_id); let expected_error_message = format!("the maximum allowed length for this field is {MAX_LENGTH}"); assert!(parsed_merchant_reference_id .is_err_and(|error_string| error_string.to_string().eq(&expected_error_message))); } #[test] fn test_invalid_ref_id_length_error_type() { let parsed_merchant_reference_id = LengthId::<MAX_LENGTH, MIN_LENGTH>::from(INVALID_REF_ID_LENGTH.into()); dbg!(&parsed_merchant_reference_id); assert!( parsed_merchant_reference_id.is_err_and(|error_type| matches!( error_type, LengthIdError::MaxLengthViolated(MAX_LENGTH) )) ); } }
crates/common_utils/src/id_type.rs
common_utils::src::id_type
2,813
true
// File: crates/common_utils/src/macros.rs // Module: common_utils::src::macros //! Utility macros #[allow(missing_docs)] #[macro_export] macro_rules! newtype_impl { ($is_pub:vis, $name:ident, $ty_path:path) => { impl core::ops::Deref for $name { type Target = $ty_path; fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for $name { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<$ty_path> for $name { fn from(ty: $ty_path) -> Self { Self(ty) } } impl $name { pub fn into_inner(self) -> $ty_path { self.0 } } }; } #[allow(missing_docs)] #[macro_export] macro_rules! newtype { ($is_pub:vis $name:ident = $ty_path:path) => { $is_pub struct $name(pub $ty_path); $crate::newtype_impl!($is_pub, $name, $ty_path); }; ($is_pub:vis $name:ident = $ty_path:path, derives = ($($trt:path),*)) => { #[derive($($trt),*)] $is_pub struct $name(pub $ty_path); $crate::newtype_impl!($is_pub, $name, $ty_path); }; } /// Use this to ensure that the corresponding /// openapi route has been implemented in the openapi crate #[macro_export] macro_rules! openapi_route { ($route_name: ident) => {{ #[cfg(feature = "openapi")] use openapi::routes::$route_name as _; $route_name }}; } #[allow(missing_docs)] #[macro_export] macro_rules! fallback_reverse_lookup_not_found { ($a:expr,$b:expr) => { match $a { Ok(res) => res, Err(err) => { router_env::logger::error!(reverse_lookup_fallback = ?err); match err.current_context() { errors::StorageError::ValueNotFound(_) => return $b, errors::StorageError::DatabaseError(data_err) => { match data_err.current_context() { diesel_models::errors::DatabaseError::NotFound => return $b, _ => return Err(err) } } _=> return Err(err) } } }; }; } /// Collects names of all optional fields that are `None`. /// This is typically useful for constructing error messages including a list of all missing fields. #[macro_export] macro_rules! collect_missing_value_keys { [$(($key:literal, $option:expr)),+] => { { let mut keys: Vec<&'static str> = Vec::new(); $( if $option.is_none() { keys.push($key); } )* keys } }; } /// Implements the `ToSql` and `FromSql` traits on a type to allow it to be serialized/deserialized /// to/from JSON data in the database. #[macro_export] macro_rules! impl_to_sql_from_sql_json { ($type:ty, $diesel_type:ty) => { #[allow(unused_qualifications)] impl diesel::serialize::ToSql<$diesel_type, diesel::pg::Pg> for $type { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { let value = serde_json::to_value(self)?; // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends // please refer to the diesel migration blog: // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations <serde_json::Value as diesel::serialize::ToSql< $diesel_type, diesel::pg::Pg, >>::to_sql(&value, &mut out.reborrow()) } } #[allow(unused_qualifications)] impl diesel::deserialize::FromSql<$diesel_type, diesel::pg::Pg> for $type { fn from_sql( bytes: <diesel::pg::Pg as diesel::backend::Backend>::RawValue<'_>, ) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< $diesel_type, diesel::pg::Pg, >>::from_sql(bytes)?; Ok(serde_json::from_value(value)?) } } }; ($type: ty) => { $crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Json); $crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Jsonb); }; } mod id_type { /// Defines an ID type. #[macro_export] macro_rules! id_type { ($type:ident, $doc:literal, $diesel_type:ty, $max_length:expr, $min_length:expr) => { #[doc = $doc] #[derive( Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, utoipa::ToSchema, )] #[diesel(sql_type = $diesel_type)] #[schema(value_type = String)] pub struct $type($crate::id_type::LengthId<$max_length, $min_length>); }; ($type:ident, $doc:literal) => { $crate::id_type!( $type, $doc, diesel::sql_types::Text, { $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH }, { $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH } ); }; } /// Defines a Global Id type #[cfg(feature = "v2")] #[macro_export] macro_rules! global_id_type { ($type:ident, $doc:literal) => { #[doc = $doc] #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct $type($crate::id_type::global_id::GlobalId); }; } /// Implements common methods on the specified ID type. #[macro_export] macro_rules! impl_id_type_methods { ($type:ty, $field_name:literal) => { impl $type { /// Get the string representation of the ID type. pub fn get_string_repr(&self) -> &str { &self.0 .0 .0 } } }; } /// Implements the `Debug` trait on the specified ID type. #[macro_export] macro_rules! impl_debug_id_type { ($type:ty) => { impl core::fmt::Debug for $type { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple(stringify!($type)) .field(&self.0 .0 .0) .finish() } } }; } /// Implements the `TryFrom<Cow<'static, str>>` trait on the specified ID type. #[macro_export] macro_rules! impl_try_from_cow_str_id_type { ($type:ty, $field_name:literal) => { impl TryFrom<std::borrow::Cow<'static, str>> for $type { type Error = error_stack::Report<$crate::errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { use error_stack::ResultExt; let merchant_ref_id = $crate::id_type::LengthId::from(value).change_context( $crate::errors::ValidationError::IncorrectValueProvided { field_name: $field_name, }, )?; Ok(Self(merchant_ref_id)) } } }; } /// Implements the `Default` trait on the specified ID type. #[macro_export] macro_rules! impl_default_id_type { ($type:ty, $prefix:literal) => { impl Default for $type { fn default() -> Self { Self($crate::generate_ref_id_with_default_length($prefix)) } } }; } /// Implements the `GenerateId` trait on the specified ID type. #[macro_export] macro_rules! impl_generate_id_id_type { ($type:ty, $prefix:literal) => { impl $crate::id_type::GenerateId for $type { fn generate() -> Self { Self($crate::generate_ref_id_with_default_length($prefix)) } } }; } /// Implements the `SerializableSecret` trait on the specified ID type. #[macro_export] macro_rules! impl_serializable_secret_id_type { ($type:ty) => { impl masking::SerializableSecret for $type {} }; } /// Implements the `ToSql` and `FromSql` traits on the specified ID type. #[macro_export] macro_rules! impl_to_sql_from_sql_id_type { ($type:ty, $diesel_type:ty, $max_length:expr, $min_length:expr) => { impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::LengthId<$max_length, $min_length>: diesel::serialize::ToSql<$diesel_type, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::LengthId<$max_length, $min_length>: diesel::deserialize::FromSql<$diesel_type, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { $crate::id_type::LengthId::<$max_length, $min_length>::from_sql(value).map(Self) } } }; ($type:ty) => { $crate::impl_to_sql_from_sql_id_type!( $type, diesel::sql_types::Text, { $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH }, { $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH } ); }; } #[cfg(feature = "v2")] /// Implements the `ToSql` and `FromSql` traits on the specified Global ID type. #[macro_export] macro_rules! impl_to_sql_from_sql_global_id_type { ($type:ty, $diesel_type:ty) => { impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::global_id::GlobalId: diesel::serialize::ToSql<$diesel_type, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<$diesel_type, DB> for $type where DB: diesel::backend::Backend, $crate::id_type::global_id::GlobalId: diesel::deserialize::FromSql<$diesel_type, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { $crate::id_type::global_id::GlobalId::from_sql(value).map(Self) } } }; ($type:ty) => { $crate::impl_to_sql_from_sql_global_id_type!($type, diesel::sql_types::Text); }; } /// Implements the `Queryable` trait on the specified ID type. #[macro_export] macro_rules! impl_queryable_id_type { ($type:ty, $diesel_type:ty) => { impl<DB> diesel::Queryable<$diesel_type, DB> for $type where DB: diesel::backend::Backend, Self: diesel::deserialize::FromSql<$diesel_type, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } }; ($type:ty) => { $crate::impl_queryable_id_type!($type, diesel::sql_types::Text); }; } } /// Create new generic list wrapper #[macro_export] macro_rules! create_list_wrapper { ( $wrapper_name:ident, $type_name: ty, impl_functions: { $($function_def: tt)* } ) => { #[derive(Clone, Debug)] pub struct $wrapper_name(Vec<$type_name>); impl $wrapper_name { pub fn new(list: Vec<$type_name>) -> Self { Self(list) } pub fn with_capacity(size: usize) -> Self { Self(Vec::with_capacity(size)) } $($function_def)* } impl std::ops::Deref for $wrapper_name { type Target = Vec<$type_name>; fn deref(&self) -> &<Self as std::ops::Deref>::Target { &self.0 } } impl std::ops::DerefMut for $wrapper_name { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl IntoIterator for $wrapper_name { type Item = $type_name; type IntoIter = std::vec::IntoIter<$type_name>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl<'a> IntoIterator for &'a $wrapper_name { type Item = &'a $type_name; type IntoIter = std::slice::Iter<'a, $type_name>; fn into_iter(self) -> Self::IntoIter { self.0.iter() } } impl FromIterator<$type_name> for $wrapper_name { fn from_iter<T: IntoIterator<Item = $type_name>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } }; } /// Get the type name for a type #[macro_export] macro_rules! type_name { ($type:ty) => { std::any::type_name::<$type>() .rsplit("::") .nth(1) .unwrap_or_default(); }; } /// **Note** Creates an enum wrapper that implements `FromStr`, `Display`, `Serialize`, and `Deserialize` /// based on a specific string representation format: `"VariantName<delimiter>FieldValue"`. /// It handles parsing errors by returning a dedicated `Invalid` variant. /// *Note*: The macro adds `Invalid,` automatically. /// /// # Use Case /// /// This macro is designed for scenarios where you need an enum, with each variant /// holding a single piece of associated data, to be easily convertible to and from /// a simple string format. This is useful for cases where enum is serialized to key value pairs /// /// It avoids more complex serialization structures (like JSON objects `{"VariantName": value}`) /// in favor of a plain string representation. /// /// # Input Enum Format and Constraints /// /// To use this macro, the enum definition must adhere to the following structure: /// /// 1. **Public Enum:** The enum must be declared as `pub enum EnumName { ... }`. /// 2. **Struct Variants Only:** All variants must be struct variants (using `{}`). /// 3. **Exactly One Field:** Each struct variant must contain *exactly one* named field. /// * **Valid:** `VariantA { value: i32 }` /// * **Invalid:** `VariantA(i32)` (tuple variant) /// * **Invalid:** `VariantA` or `VariantA {}` (no field) /// * **Invalid:** `VariantA { value: i32, other: bool }` (multiple fields) /// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimiter` literal, /// which is the character used to separate the variant name from the field data in /// the string representation (e.g., `tag_delimiter = ":",`). /// 5. **Field Type Requirements:** The type of the single field in each variant (`$field_ty`) /// must implement: /// * `core::str::FromStr`: To parse the field's data from the string part. /// The `Err` type should ideally be convertible to a meaningful error, though the /// macro currently uses a generic error message upon failure. /// * `core::fmt::Display`: To convert the field's data into the string part. /// * `serde::Serialize` and `serde::Deserialize<'de>`: Although the macro implements /// custom `Serialize`/`Deserialize` for the *enum* using the string format, the field /// type itself must satisfy these bounds if required elsewhere or by generic contexts. /// The macro's implementations rely solely on `Display` and `FromStr` for the conversion. /// 6. **Error Type:** This macro uses `core::convert::Infallible` as it never fails but gives /// `Self::Invalid` variant. /// /// # Serialization and Deserialization (`serde`) /// /// When `serde` features are enabled and the necessary traits are derived or implemented, /// this macro implements `Serialize` and `Deserialize` for the enum: /// /// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimiter = ":",`) /// will be serialized into the string `"VariantA:123"`. If serializing to JSON, this results /// in a JSON string: `"\"VariantA:123\""`. /// **Deserialization:** The macro expects a string matching the format `"VariantName<delimiter>FieldValue"`. /// It uses the enum's `FromStr` implementation internally. When deserializing from JSON, it /// expects a JSON string containing the correctly formatted value (e.g., `"\"VariantA:123\""`). /// /// # `Display` and `FromStr` /// /// **`Display`:** Formats valid variants to `"VariantName<delimiter>FieldValue"` and catch-all cases to `"Invalid"`. /// **`FromStr`:** Parses `"VariantName<delimiter>FieldValue"` to the variant, or returns `Self::Invalid` /// if the input string is malformed or `"Invalid"`. /// /// # Example /// /// ```rust /// use std::str::FromStr; /// /// crate::impl_enum_str!( /// tag_delimiter = ":", /// #[derive(Debug, PartialEq, Clone)] // Add other derives as needed /// pub enum Setting { /// Timeout { duration_ms: u32 }, /// Username { name: String }, /// } /// ); /// // Note: The macro adds `Invalid,` automatically. /// /// fn main() { /// // Display /// let setting1 = Setting::Timeout { duration_ms: 5000 }; /// assert_eq!(setting1.to_string(), "Timeout:5000"); /// assert_eq!(Setting::Invalid.to_string(), "Invalid"); /// /// // FromStr (returns Self, not Result) /// let parsed_setting: Setting = "Username:admin".parse().expect("Valid parse"); // parse() itself doesn't panic /// assert_eq!(parsed_setting, Setting::Username { name: "admin".to_string() }); /// /// let invalid_format: Setting = "Timeout".parse().expect("Parse always returns Self"); /// assert_eq!(invalid_format, Setting::Invalid); // Malformed input yields Invalid /// /// let bad_data: Setting = "Timeout:fast".parse().expect("Parse always returns Self"); /// assert_eq!(bad_data, Setting::Invalid); // Bad field data yields Invalid /// /// let unknown_tag: Setting = "Unknown:abc".parse().expect("Parse always returns Self"); /// assert_eq!(unknown_tag, Setting::Invalid); // Unknown tag yields Invalid /// /// let explicit_invalid: Setting = "Invalid".parse().expect("Parse always returns Self"); /// assert_eq!(explicit_invalid, Setting::Invalid); // "Invalid" string yields Invalid /// /// // Serde (requires derive Serialize/Deserialize on Setting) /// // let json_output = serde_json::to_string(&setting1).unwrap(); /// // assert_eq!(json_output, "\"Timeout:5000\""); /// // let invalid_json_output = serde_json::to_string(&Setting::Invalid).unwrap(); /// // assert_eq!(invalid_json_output, "\"Invalid\""); /// /// // let deserialized: Setting = serde_json::from_str("\"Username:guest\"").unwrap(); /// // assert_eq!(deserialized, Setting::Username { name: "guest".to_string() }); /// // let deserialized_invalid: Setting = serde_json::from_str("\"Invalid\"").unwrap(); /// // assert_eq!(deserialized_invalid, Setting::Invalid); /// // let deserialized_malformed: Setting = serde_json::from_str("\"TimeoutFast\"").unwrap(); /// // assert_eq!(deserialized_malformed, Setting::Invalid); // Malformed -> Invalid /// } /// /// # // Mock macro definition for doctest purposes /// # #[macro_export] macro_rules! impl_enum_str { ($($tt:tt)*) => { $($tt)* } } /// ``` #[macro_export] macro_rules! impl_enum_str { ( tag_delimiter = $tag_delim:literal, $(#[$enum_attr:meta])* pub enum $enum_name:ident { $( $(#[$variant_attr:meta])* $variant:ident { $(#[$field_attr:meta])* $field:ident : $field_ty:ty $(,)? } ),* $(,)? } ) => { $(#[$enum_attr])* pub enum $enum_name { $( $(#[$variant_attr])* $variant { $(#[$field_attr])* $field : $field_ty }, )* /// Represents a parsing failure. Invalid, // Automatically add the Invalid variant } // Implement FromStr - now returns Self, not Result impl core::str::FromStr for $enum_name { // No associated error type needed type Err = core::convert::Infallible; // FromStr requires an Err type, use Infallible fn from_str(s: &str) -> Result<Self, Self::Err> { // Check for explicit "Invalid" string first if s == "Invalid" { return Ok(Self::Invalid); } let Some((tag, associated_data)) = s.split_once($tag_delim) else { // Missing delimiter -> Invalid return Ok(Self::Invalid); }; let result = match tag { $( stringify!($variant) => { // Try to parse the field data match associated_data.parse::<$field_ty>() { Ok(parsed_field) => { // Success -> construct the variant Self::$variant { $field: parsed_field } }, Err(_) => { // Field parse failure -> Invalid Self::Invalid } } } ),* // Unknown tag -> Invalid _ => Self::Invalid, }; Ok(result) // Always Ok because failure modes return Self::Invalid } } // Implement Serialize impl ::serde::Serialize for $enum_name { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer, { match self { $( Self::$variant { $field } => { let s = format!("{}{}{}", stringify!($variant), $tag_delim, $field); serializer.serialize_str(&s) } )* // Handle Invalid variant Self::Invalid => serializer.serialize_str("Invalid"), } } } // Implement Deserialize impl<'de> ::serde::Deserialize<'de> for $enum_name { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de>, { struct EnumVisitor; impl<'de> ::serde::de::Visitor<'de> for EnumVisitor { type Value = $enum_name; fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { formatter.write_str(concat!("a string like VariantName", $tag_delim, "field_data or 'Invalid'")) } // Leverage the FromStr implementation which now returns Self::Invalid on failure fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: ::serde::de::Error, { // parse() now returns Result<Self, Infallible> // We unwrap() the Ok because it's infallible. Ok(value.parse::<$enum_name>().unwrap()) } fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: ::serde::de::Error, { Ok(value.parse::<$enum_name>().unwrap()) } } deserializer.deserialize_str(EnumVisitor) } } // Implement Display impl core::fmt::Display for $enum_name { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { $( Self::$variant { $field } => { write!(f, "{}{}{}", stringify!($variant), $tag_delim, $field) } )* // Handle Invalid variant Self::Invalid => write!(f, "Invalid"), } } } }; } // --- Tests --- #[cfg(test)] mod tests { #![allow(clippy::panic, clippy::expect_used)] use serde_json::{json, Value as JsonValue}; use crate::impl_enum_str; impl_enum_str!( tag_delimiter = ":", #[derive(Debug, PartialEq, Clone)] pub enum TestEnum { VariantA { value: i32 }, VariantB { text: String }, VariantC { id: u64 }, VariantJson { data: JsonValue }, } // Note: Invalid variant is added automatically by the macro ); #[test] fn test_enum_from_str_ok() { // Success cases just parse directly let parsed_a: TestEnum = "VariantA:42".parse().unwrap(); // Unwrapping Infallible is fine assert_eq!(parsed_a, TestEnum::VariantA { value: 42 }); let parsed_b: TestEnum = "VariantB:hello world".parse().unwrap(); assert_eq!( parsed_b, TestEnum::VariantB { text: "hello world".to_string() } ); let parsed_c: TestEnum = "VariantC:123456789012345".parse().unwrap(); assert_eq!( parsed_c, TestEnum::VariantC { id: 123456789012345 } ); let parsed_json: TestEnum = r#"VariantJson:{"ok":true}"#.parse().unwrap(); assert_eq!( parsed_json, TestEnum::VariantJson { data: json!({"ok": true}) } ); } #[test] fn test_enum_from_str_failures_yield_invalid() { // Missing delimiter let parsed: TestEnum = "VariantA".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Unknown tag let parsed: TestEnum = "UnknownVariant:123".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Bad field data for i32 let parsed: TestEnum = "VariantA:not_a_number".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Bad field data for JsonValue let parsed: TestEnum = r#"VariantJson:{"bad_json"#.parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Empty field data for non-string (e.g., i32) let parsed: TestEnum = "VariantA:".parse().unwrap(); assert_eq!(parsed, TestEnum::Invalid); // Empty field data for string IS valid for String type let parsed_str: TestEnum = "VariantB:".parse().unwrap(); assert_eq!( parsed_str, TestEnum::VariantB { text: "".to_string() } ); // Parsing the literal "Invalid" string let parsed_invalid_str: TestEnum = "Invalid".parse().unwrap(); assert_eq!(parsed_invalid_str, TestEnum::Invalid); } #[test] fn test_enum_display_and_serialize() { // Display valid let value_a = TestEnum::VariantA { value: 99 }; assert_eq!(value_a.to_string(), "VariantA:99"); // Serialize valid let json_a = serde_json::to_string(&value_a).expect("Serialize A failed"); assert_eq!(json_a, "\"VariantA:99\""); // Serializes to JSON string // Display Invalid let value_invalid = TestEnum::Invalid; assert_eq!(value_invalid.to_string(), "Invalid"); // Serialize Invalid let json_invalid = serde_json::to_string(&value_invalid).expect("Serialize Invalid failed"); assert_eq!(json_invalid, "\"Invalid\""); // Serializes to JSON string "Invalid" } #[test] fn test_enum_deserialize() { // Deserialize valid let input_a = "\"VariantA:123\""; let deserialized_a: TestEnum = serde_json::from_str(input_a).expect("Deserialize A failed"); assert_eq!(deserialized_a, TestEnum::VariantA { value: 123 }); // Deserialize explicit "Invalid" let input_invalid = "\"Invalid\""; let deserialized_invalid: TestEnum = serde_json::from_str(input_invalid).expect("Deserialize Invalid failed"); assert_eq!(deserialized_invalid, TestEnum::Invalid); // Deserialize malformed string (according to macro rules) -> Invalid let input_malformed = "\"VariantA_no_delimiter\""; let deserialized_malformed: TestEnum = serde_json::from_str(input_malformed).expect("Deserialize malformed should succeed"); assert_eq!(deserialized_malformed, TestEnum::Invalid); // Deserialize string with bad field data -> Invalid let input_bad_data = "\"VariantA:not_a_number\""; let deserialized_bad_data: TestEnum = serde_json::from_str(input_bad_data).expect("Deserialize bad data should succeed"); assert_eq!(deserialized_bad_data, TestEnum::Invalid); } }
crates/common_utils/src/macros.rs
common_utils::src::macros
6,932
true
// File: crates/common_utils/src/payout_method_utils.rs // Module: common_utils::src::payout_method_utils //! This module has common utilities for payout method data in HyperSwitch use common_enums; use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow}; use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::new_type::{ MaskedBankAccount, MaskedBic, MaskedEmail, MaskedIban, MaskedPhoneNumber, MaskedRoutingNumber, MaskedSortCode, }; /// Masked payout method details for storing in db #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub enum AdditionalPayoutMethodData { /// Additional data for card payout method Card(Box<CardAdditionalData>), /// Additional data for bank payout method Bank(Box<BankAdditionalData>), /// Additional data for wallet payout method Wallet(Box<WalletAdditionalData>), /// Additional data for Bank Redirect payout method BankRedirect(Box<BankRedirectAdditionalData>), } crate::impl_to_sql_from_sql_json!(AdditionalPayoutMethodData); /// Masked payout method details for card payout method #[derive( Eq, PartialEq, Clone, Debug, Serialize, Deserialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct CardAdditionalData { /// Issuer of the card pub card_issuer: Option<String>, /// Card network of the card #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<common_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, /// Card issuing country pub card_issuing_country: Option<String>, /// Code for Card issuing bank pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, /// Card expiry month #[schema(value_type = String, example = "01")] pub card_exp_month: Option<Secret<String>>, /// Card expiry year #[schema(value_type = String, example = "2026")] pub card_exp_year: Option<Secret<String>>, /// Card holder name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } /// Masked payout method details for bank payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(untagged)] pub enum BankAdditionalData { /// Additional data for ach bank transfer payout method Ach(Box<AchBankTransferAdditionalData>), /// Additional data for bacs bank transfer payout method Bacs(Box<BacsBankTransferAdditionalData>), /// Additional data for sepa bank transfer payout method Sepa(Box<SepaBankTransferAdditionalData>), /// Additional data for pix bank transfer payout method Pix(Box<PixBankTransferAdditionalData>), } /// Masked payout method details for ach bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct AchBankTransferAdditionalData { /// Partially masked account number for ach bank debit payment #[schema(value_type = String, example = "0001****3456")] pub bank_account_number: MaskedBankAccount, /// Partially masked routing number for ach bank debit payment #[schema(value_type = String, example = "110***000")] pub bank_routing_number: MaskedRoutingNumber, /// Name of the bank #[schema(value_type = Option<BankNames>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<common_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, } /// Masked payout method details for bacs bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct BacsBankTransferAdditionalData { /// Partially masked sort code for Bacs payment method #[schema(value_type = String, example = "108800")] pub bank_sort_code: MaskedSortCode, /// Bank account's owner name #[schema(value_type = String, example = "0001****3456")] pub bank_account_number: MaskedBankAccount, /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<common_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, } /// Masked payout method details for sepa bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct SepaBankTransferAdditionalData { /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = String, example = "DE8937******013000")] pub iban: MaskedIban, /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<common_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = Option<String>, example = "HSBCGB2LXXX")] pub bic: Option<MaskedBic>, } /// Masked payout method details for pix bank transfer payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct PixBankTransferAdditionalData { /// Partially masked unique key for pix transfer #[schema(value_type = String, example = "a1f4102e ****** 6fa48899c1d1")] pub pix_key: MaskedBankAccount, /// Partially masked CPF - CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "**** 124689")] pub tax_id: Option<MaskedBankAccount>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "**** 23456")] pub bank_account_number: MaskedBankAccount, /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, } /// Masked payout method details for wallet payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(untagged)] pub enum WalletAdditionalData { /// Additional data for paypal wallet payout method Paypal(Box<PaypalAdditionalData>), /// Additional data for venmo wallet payout method Venmo(Box<VenmoAdditionalData>), /// Additional data for Apple pay decrypt wallet payout method ApplePayDecrypt(Box<ApplePayDecryptAdditionalData>), } /// Masked payout method details for paypal wallet payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct PaypalAdditionalData { /// Email linked with paypal account #[schema(value_type = Option<String>, example = "[email protected]")] pub email: Option<MaskedEmail>, /// mobile number linked to paypal account #[schema(value_type = Option<String>, example = "******* 3349")] pub telephone_number: Option<MaskedPhoneNumber>, /// id of the paypal account #[schema(value_type = Option<String>, example = "G83K ***** HCQ2")] pub paypal_id: Option<MaskedBankAccount>, } /// Masked payout method details for venmo wallet payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct VenmoAdditionalData { /// mobile number linked to venmo account #[schema(value_type = Option<String>, example = "******* 3349")] pub telephone_number: Option<MaskedPhoneNumber>, } /// Masked payout method details for Apple pay decrypt wallet payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct ApplePayDecryptAdditionalData { /// Card expiry month #[schema(value_type = String, example = "01")] pub card_exp_month: Secret<String>, /// Card expiry year #[schema(value_type = String, example = "2026")] pub card_exp_year: Secret<String>, /// Card holder name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } /// Masked payout method details for wallet payout method #[derive( Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] #[serde(untagged)] pub enum BankRedirectAdditionalData { /// Additional data for interac bank redirect payout method Interac(Box<InteracAdditionalData>), } /// Masked payout method details for interac bank redirect payout method #[derive( Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema, )] #[diesel(sql_type = Jsonb)] pub struct InteracAdditionalData { /// Email linked with interac account #[schema(value_type = Option<String>, example = "[email protected]")] pub email: Option<MaskedEmail>, }
crates/common_utils/src/payout_method_utils.rs
common_utils::src::payout_method_utils
2,511
true
// File: crates/common_utils/src/link_utils.rs // Module: common_utils::src::link_utils //! This module has common utilities for links in HyperSwitch use std::{collections::HashSet, primitive::i64}; use common_enums::{enums, UIWidgetFormLayout}; use diesel::{ backend::Backend, deserialize, deserialize::FromSql, serialize::{Output, ToSql}, sql_types::Jsonb, AsExpression, FromSqlRow, }; use error_stack::{report, ResultExt}; use masking::Secret; use regex::Regex; #[cfg(feature = "logs")] use router_env::logger; use serde::Serialize; use utoipa::ToSchema; use crate::{consts, errors::ParsingError, id_type, types::MinorUnit}; #[derive( Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema, )] #[serde(rename_all = "snake_case", tag = "type", content = "value")] #[diesel(sql_type = Jsonb)] /// Link status enum pub enum GenericLinkStatus { /// Status variants for payment method collect link PaymentMethodCollect(PaymentMethodCollectStatus), /// Status variants for payout link PayoutLink(PayoutLinkStatus), } impl Default for GenericLinkStatus { fn default() -> Self { Self::PaymentMethodCollect(PaymentMethodCollectStatus::Initiated) } } crate::impl_to_sql_from_sql_json!(GenericLinkStatus); #[derive( Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema, )] #[serde(rename_all = "snake_case")] #[diesel(sql_type = Jsonb)] /// Status variants for payment method collect links pub enum PaymentMethodCollectStatus { /// Link was initialized Initiated, /// Link was expired or invalidated Invalidated, /// Payment method details were submitted Submitted, } impl<DB: Backend> FromSql<Jsonb, DB> for PaymentMethodCollectStatus where serde_json::Value: FromSql<Jsonb, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; let generic_status: GenericLinkStatus = serde_json::from_value(value)?; match generic_status { GenericLinkStatus::PaymentMethodCollect(status) => Ok(status), GenericLinkStatus::PayoutLink(_) => Err(report!(ParsingError::EnumParseFailure( "PaymentMethodCollectStatus" ))) .attach_printable("Invalid status for PaymentMethodCollect")?, } } } impl ToSql<Jsonb, diesel::pg::Pg> for PaymentMethodCollectStatus where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, { // This wraps PaymentMethodCollectStatus with GenericLinkStatus // Required for storing the status in required format in DB (GenericLinkStatus) // This type is used in PaymentMethodCollectLink (a variant of GenericLink, used in the application for avoiding conversion of data and status) fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { let value = serde_json::to_value(GenericLinkStatus::PaymentMethodCollect(self.clone()))?; // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends // please refer to the diesel migration blog: // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) } } #[derive( Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema, )] #[serde(rename_all = "snake_case")] #[diesel(sql_type = Jsonb)] /// Status variants for payout links pub enum PayoutLinkStatus { /// Link was initialized Initiated, /// Link was expired or invalidated Invalidated, /// Payout details were submitted Submitted, } impl<DB: Backend> FromSql<Jsonb, DB> for PayoutLinkStatus where serde_json::Value: FromSql<Jsonb, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; let generic_status: GenericLinkStatus = serde_json::from_value(value)?; match generic_status { GenericLinkStatus::PayoutLink(status) => Ok(status), GenericLinkStatus::PaymentMethodCollect(_) => { Err(report!(ParsingError::EnumParseFailure("PayoutLinkStatus"))) .attach_printable("Invalid status for PayoutLink")? } } } } impl ToSql<Jsonb, diesel::pg::Pg> for PayoutLinkStatus where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, { // This wraps PayoutLinkStatus with GenericLinkStatus // Required for storing the status in required format in DB (GenericLinkStatus) // This type is used in PayoutLink (a variant of GenericLink, used in the application for avoiding conversion of data and status) fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { let value = serde_json::to_value(GenericLinkStatus::PayoutLink(self.clone()))?; // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends // please refer to the diesel migration blog: // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) } } #[derive(Serialize, serde::Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)] #[diesel(sql_type = Jsonb)] /// Payout link object pub struct PayoutLinkData { /// Identifier for the payout link pub payout_link_id: String, /// Identifier for the customer pub customer_id: id_type::CustomerId, /// Identifier for the payouts resource pub payout_id: id_type::PayoutId, /// Link to render the payout link pub link: url::Url, /// Client secret generated for authenticating frontend APIs pub client_secret: Secret<String>, /// Expiry in seconds from the time it was created pub session_expiry: u32, #[serde(flatten)] /// Payout link's UI configurations pub ui_config: GenericLinkUiConfig, /// List of enabled payment methods pub enabled_payment_methods: Option<Vec<EnabledPaymentMethod>>, /// Payout amount pub amount: MinorUnit, /// Payout currency pub currency: enums::Currency, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: HashSet<String>, /// Form layout of the payout link pub form_layout: Option<UIWidgetFormLayout>, /// `test_mode` can be used for testing payout links without any restrictions pub test_mode: Option<bool>, } crate::impl_to_sql_from_sql_json!(PayoutLinkData); /// Object for GenericLinkUiConfig #[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)] pub struct GenericLinkUiConfig { /// Merchant's display logo #[schema(value_type = Option<String>, max_length = 255, example = "https://hyperswitch.io/favicon.ico")] pub logo: Option<url::Url>, /// Custom merchant name for the link #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch")] pub merchant_name: Option<Secret<String>>, /// Primary color to be used in the form represented in hex format #[schema(value_type = Option<String>, max_length = 255, example = "#4285F4")] pub theme: Option<String>, } /// Object for GenericLinkUiConfigFormData #[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)] pub struct GenericLinkUiConfigFormData { /// Merchant's display logo #[schema(value_type = String, max_length = 255, example = "https://hyperswitch.io/favicon.ico")] pub logo: url::Url, /// Custom merchant name for the link #[schema(value_type = String, max_length = 255, example = "Hyperswitch")] pub merchant_name: Secret<String>, /// Primary color to be used in the form represented in hex format #[schema(value_type = String, max_length = 255, example = "#4285F4")] pub theme: String, } /// Object for EnabledPaymentMethod #[derive(Clone, Debug, Serialize, serde::Deserialize, ToSchema)] pub struct EnabledPaymentMethod { /// Payment method (banks, cards, wallets) enabled for the operation #[schema(value_type = PaymentMethod)] pub payment_method: enums::PaymentMethod, /// An array of associated payment method types #[schema(value_type = HashSet<PaymentMethodType>)] pub payment_method_types: HashSet<enums::PaymentMethodType>, } /// Util function for validating a domain without any wildcard characters. pub fn validate_strict_domain(domain: &str) -> bool { Regex::new(consts::STRICT_DOMAIN_REGEX) .map(|regex| regex.is_match(domain)) .map_err(|err| { let err_msg = format!("Invalid strict domain regex: {err:?}"); #[cfg(feature = "logs")] logger::error!(err_msg); err_msg }) .unwrap_or(false) } /// Util function for validating a domain with "*" wildcard characters. pub fn validate_wildcard_domain(domain: &str) -> bool { Regex::new(consts::WILDCARD_DOMAIN_REGEX) .map(|regex| regex.is_match(domain)) .map_err(|err| { let err_msg = format!("Invalid strict domain regex: {err:?}"); #[cfg(feature = "logs")] logger::error!(err_msg); err_msg }) .unwrap_or(false) } #[cfg(test)] mod domain_tests { use regex::Regex; use super::*; #[test] fn test_validate_strict_domain_regex() { assert!( Regex::new(consts::STRICT_DOMAIN_REGEX).is_ok(), "Strict domain regex is invalid" ); } #[test] fn test_validate_wildcard_domain_regex() { assert!( Regex::new(consts::WILDCARD_DOMAIN_REGEX).is_ok(), "Wildcard domain regex is invalid" ); } #[test] fn test_validate_strict_domain() { let valid_domains = vec![ "example.com", "example.subdomain.com", "https://example.com:8080", "http://example.com", "example.com:8080", "example.com:443", "localhost:443", "127.0.0.1:443", ]; for domain in valid_domains { assert!( validate_strict_domain(domain), "Could not validate strict domain: {domain}", ); } let invalid_domains = vec![ "", "invalid.domain.", "not_a_domain", "http://example.com/path?query=1#fragment", "127.0.0.1.2:443", ]; for domain in invalid_domains { assert!( !validate_strict_domain(domain), "Could not validate invalid strict domain: {domain}", ); } } #[test] fn test_validate_wildcard_domain() { let valid_domains = vec![ "example.com", "example.subdomain.com", "https://example.com:8080", "http://example.com", "example.com:8080", "example.com:443", "localhost:443", "127.0.0.1:443", "*.com", "example.*.com", "example.com:*", "*:443", "localhost:*", "127.0.0.*:*", "*:*", ]; for domain in valid_domains { assert!( validate_wildcard_domain(domain), "Could not validate wildcard domain: {domain}", ); } let invalid_domains = vec![ "", "invalid.domain.", "not_a_domain", "http://example.com/path?query=1#fragment", "*.", ".*", "example.com:*:", "*:443:", ":localhost:*", "127.00.*:*", ]; for domain in invalid_domains { assert!( !validate_wildcard_domain(domain), "Could not validate invalid wildcard domain: {domain}", ); } } }
crates/common_utils/src/link_utils.rs
common_utils::src::link_utils
2,918
true
// File: crates/common_utils/src/crypto.rs // Module: common_utils::src::crypto //! Utilities for cryptographic algorithms use std::ops::Deref; use base64::Engine; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use md5; use pem; use ring::{ aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey}, hmac, rand as ring_rand, signature::{RsaKeyPair, RSA_PSS_SHA256}, }; #[cfg(feature = "logs")] use router_env::logger; use rsa::{pkcs8::DecodePublicKey, signature::Verifier}; use crate::{ consts::BASE64_ENGINE, errors::{self, CustomResult}, pii::{self, EncryptionStrategy}, }; #[derive(Clone, Debug)] struct NonceSequence(u128); impl NonceSequence { /// Byte index at which sequence number starts in a 16-byte (128-bit) sequence. /// This byte index considers the big endian order used while encoding and decoding the nonce /// to/from a 128-bit unsigned integer. const SEQUENCE_NUMBER_START_INDEX: usize = 4; /// Generate a random nonce sequence. fn new() -> Result<Self, ring::error::Unspecified> { use ring::rand::{SecureRandom, SystemRandom}; let rng = SystemRandom::new(); // 96-bit sequence number, stored in a 128-bit unsigned integer in big-endian order let mut sequence_number = [0_u8; 128 / 8]; rng.fill(&mut sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..])?; let sequence_number = u128::from_be_bytes(sequence_number); Ok(Self(sequence_number)) } /// Returns the current nonce value as bytes. fn current(&self) -> [u8; aead::NONCE_LEN] { let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); nonce } /// Constructs a nonce sequence from bytes fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self { let mut sequence_number = [0_u8; 128 / 8]; sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes); let sequence_number = u128::from_be_bytes(sequence_number); Self(sequence_number) } } impl aead::NonceSequence for NonceSequence { fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> { let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); // Increment sequence number self.0 = self.0.wrapping_add(1); // Return previous sequence number as bytes Ok(aead::Nonce::assume_unique_for_key(nonce)) } } /// Trait for cryptographically signing messages pub trait SignMessage { /// Takes in a secret and a message and returns the calculated signature as bytes fn sign_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Trait for cryptographically verifying a message against a signature pub trait VerifySignature { /// Takes in a secret, the signature and the message and verifies the message /// against the signature fn verify_signature( &self, _secret: &[u8], _signature: &[u8], _msg: &[u8], ) -> CustomResult<bool, errors::CryptoError>; } /// Trait for cryptographically encoding a message pub trait EncodeMessage { /// Takes in a secret and the message and encodes it, returning bytes fn encode_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Trait for cryptographically decoding a message pub trait DecodeMessage { /// Takes in a secret, an encoded messages and attempts to decode it, returning bytes fn decode_message( &self, _secret: &[u8], _msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Represents no cryptographic algorithm. /// Implements all crypto traits and acts like a Nop #[derive(Debug)] pub struct NoAlgorithm; impl SignMessage for NoAlgorithm { fn sign_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(Vec::new()) } } impl VerifySignature for NoAlgorithm { fn verify_signature( &self, _secret: &[u8], _signature: &[u8], _msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { Ok(true) } } impl EncodeMessage for NoAlgorithm { fn encode_message( &self, _secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(msg.to_vec()) } } impl DecodeMessage for NoAlgorithm { fn decode_message( &self, _secret: &[u8], msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(msg.expose()) } } /// Represents the HMAC-SHA-1 algorithm #[derive(Debug)] pub struct HmacSha1; impl SignMessage for HmacSha1 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha1 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Represents the HMAC-SHA-256 algorithm #[derive(Debug)] pub struct HmacSha256; impl SignMessage for HmacSha256 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA256, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha256 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA256, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Represents the HMAC-SHA-512 algorithm #[derive(Debug)] pub struct HmacSha512; impl SignMessage for HmacSha512 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA512, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha512 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA512, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Blake3 #[derive(Debug)] pub struct Blake3(String); impl Blake3 { /// Create a new instance of Blake3 with a key pub fn new(key: impl Into<String>) -> Self { Self(key.into()) } } impl SignMessage for Blake3 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = blake3::derive_key(&self.0, secret); let output = blake3::keyed_hash(&key, msg).as_bytes().to_vec(); Ok(output) } } impl VerifySignature for Blake3 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = blake3::derive_key(&self.0, secret); let output = blake3::keyed_hash(&key, msg); Ok(output.as_bytes() == signature) } } /// Represents the GCM-AES-256 algorithm #[derive(Debug)] pub struct GcmAes256; impl EncodeMessage for GcmAes256 { fn encode_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let nonce_sequence = NonceSequence::new().change_context(errors::CryptoError::EncodingFailed)?; let current_nonce = nonce_sequence.current(); let key = UnboundKey::new(&aead::AES_256_GCM, secret) .change_context(errors::CryptoError::EncodingFailed)?; let mut key = SealingKey::new(key, nonce_sequence); let mut in_out = msg.to_vec(); key.seal_in_place_append_tag(aead::Aad::empty(), &mut in_out) .change_context(errors::CryptoError::EncodingFailed)?; in_out.splice(0..0, current_nonce); Ok(in_out) } } impl DecodeMessage for GcmAes256 { fn decode_message( &self, secret: &[u8], msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError> { let msg = msg.expose(); let key = UnboundKey::new(&aead::AES_256_GCM, secret) .change_context(errors::CryptoError::DecodingFailed)?; let nonce_sequence = NonceSequence::from_bytes( <[u8; aead::NONCE_LEN]>::try_from( msg.get(..aead::NONCE_LEN) .ok_or(errors::CryptoError::DecodingFailed) .attach_printable("Failed to read the nonce form the encrypted ciphertext")?, ) .change_context(errors::CryptoError::DecodingFailed)?, ); let mut key = OpeningKey::new(key, nonce_sequence); let mut binding = msg; let output = binding.as_mut_slice(); let result = key .open_within(aead::Aad::empty(), output, aead::NONCE_LEN..) .change_context(errors::CryptoError::DecodingFailed)?; Ok(result.to_vec()) } } /// Represents the ED25519 signature verification algorithm #[derive(Debug)] pub struct Ed25519; impl Ed25519 { /// ED25519 algorithm constants const ED25519_PUBLIC_KEY_LEN: usize = 32; const ED25519_SIGNATURE_LEN: usize = 64; /// Validates ED25519 inputs (public key and signature lengths) fn validate_inputs( public_key: &[u8], signature: &[u8], ) -> CustomResult<(), errors::CryptoError> { // Validate public key length if public_key.len() != Self::ED25519_PUBLIC_KEY_LEN { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 public key length: expected {} bytes, got {}", Self::ED25519_PUBLIC_KEY_LEN, public_key.len() )); } // Validate signature length if signature.len() != Self::ED25519_SIGNATURE_LEN { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 signature length: expected {} bytes, got {}", Self::ED25519_SIGNATURE_LEN, signature.len() )); } Ok(()) } } impl VerifySignature for Ed25519 { fn verify_signature( &self, public_key: &[u8], signature: &[u8], // ED25519 signature bytes (must be 64 bytes) msg: &[u8], // Message that was signed ) -> CustomResult<bool, errors::CryptoError> { // Validate inputs first Self::validate_inputs(public_key, signature)?; // Create unparsed public key let ring_public_key = ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key); // Perform verification match ring_public_key.verify(msg, signature) { Ok(()) => Ok(true), Err(_err) => { #[cfg(feature = "logs")] logger::error!("ED25519 signature verification failed: {:?}", _err); Err(errors::CryptoError::SignatureVerificationFailed) .attach_printable("ED25519 signature verification failed") } } } } impl SignMessage for Ed25519 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { if secret.len() != 32 { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 private key length: expected 32 bytes, got {}", secret.len() )); } let key_pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(secret) .change_context(errors::CryptoError::MessageSigningFailed) .attach_printable("Failed to create ED25519 key pair from seed")?; let signature = key_pair.sign(msg); Ok(signature.as_ref().to_vec()) } } /// Secure Hash Algorithm 512 #[derive(Debug)] pub struct Sha512; /// Secure Hash Algorithm 256 #[derive(Debug)] pub struct Sha256; /// Trait for generating a digest for SHA pub trait GenerateDigest { /// takes a message and creates a digest for it fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError>; } impl GenerateDigest for Sha512 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = ring::digest::digest(&ring::digest::SHA512, message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Sha512 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let msg_str = std::str::from_utf8(msg) .change_context(errors::CryptoError::EncodingFailed)? .to_owned(); let hashed_digest = hex::encode( Self.generate_digest(msg_str.as_bytes()) .change_context(errors::CryptoError::SignatureVerificationFailed)?, ); let hashed_digest_into_bytes = hashed_digest.into_bytes(); Ok(hashed_digest_into_bytes == signature) } } /// MD5 hash function #[derive(Debug)] pub struct Md5; impl GenerateDigest for Md5 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = md5::compute(message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Md5 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let hashed_digest = Self .generate_digest(msg) .change_context(errors::CryptoError::SignatureVerificationFailed)?; Ok(hashed_digest == signature) } } impl GenerateDigest for Sha256 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = ring::digest::digest(&ring::digest::SHA256, message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Sha256 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let hashed_digest = Self .generate_digest(msg) .change_context(errors::CryptoError::SignatureVerificationFailed)?; let hashed_digest_into_bytes = hashed_digest.as_slice(); Ok(hashed_digest_into_bytes == signature) } } /// Secure Hash Algorithm 256 with RSA public-key cryptosystem #[derive(Debug)] pub struct RsaSha256; impl VerifySignature for RsaSha256 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { // create verifying key let decoded_public_key = BASE64_ENGINE .decode(secret) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("base64 decoding failed")?; let string_public_key = String::from_utf8(decoded_public_key) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("utf8 to string parsing failed")?; let rsa_public_key = rsa::RsaPublicKey::from_public_key_pem(&string_public_key) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("rsa public key transformation failed")?; let verifying_key = rsa::pkcs1v15::VerifyingKey::<rsa::sha2::Sha256>::new(rsa_public_key); // transfrom the signature let decoded_signature = BASE64_ENGINE .decode(signature) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("base64 decoding failed")?; let rsa_signature = rsa::pkcs1v15::Signature::try_from(&decoded_signature[..]) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("rsa signature transformation failed")?; // signature verification verifying_key .verify(msg, &rsa_signature) .map(|_| true) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("signature verification step failed") } } /// TripleDesEde3 hash function #[derive(Debug)] #[cfg(feature = "crypto_openssl")] pub struct TripleDesEde3CBC { padding: common_enums::CryptoPadding, iv: Vec<u8>, } #[cfg(feature = "crypto_openssl")] impl TripleDesEde3CBC { const TRIPLE_DES_KEY_LENGTH: usize = 24; /// Initialization Vector (IV) length for TripleDesEde3 pub const TRIPLE_DES_IV_LENGTH: usize = 8; /// Constructor function to be used by the encryptor and decryptor to generate the data type pub fn new( padding: Option<common_enums::CryptoPadding>, iv: Vec<u8>, ) -> Result<Self, errors::CryptoError> { if iv.len() != Self::TRIPLE_DES_IV_LENGTH { Err(errors::CryptoError::InvalidIvLength)? }; let padding = padding.unwrap_or(common_enums::CryptoPadding::PKCS7); Ok(Self { iv, padding }) } } #[cfg(feature = "crypto_openssl")] impl EncodeMessage for TripleDesEde3CBC { fn encode_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { if secret.len() != Self::TRIPLE_DES_KEY_LENGTH { Err(errors::CryptoError::InvalidKeyLength)? } let mut buffer = msg.to_vec(); if let common_enums::CryptoPadding::ZeroPadding = self.padding { let pad_len = Self::TRIPLE_DES_IV_LENGTH - (buffer.len() % Self::TRIPLE_DES_IV_LENGTH); if pad_len != Self::TRIPLE_DES_IV_LENGTH { buffer.extend(vec![0u8; pad_len]); } }; let cipher = openssl::symm::Cipher::des_ede3_cbc(); openssl::symm::encrypt(cipher, secret, Some(&self.iv), &buffer) .change_context(errors::CryptoError::EncodingFailed) } } /// Generate a random string using a cryptographically secure pseudo-random number generator /// (CSPRNG). Typically used for generating (readable) keys and passwords. #[inline] pub fn generate_cryptographically_secure_random_string(length: usize) -> String { use rand::distributions::DistString; rand::distributions::Alphanumeric.sample_string(&mut rand::rngs::OsRng, length) } /// Generate an array of random bytes using a cryptographically secure pseudo-random number /// generator (CSPRNG). Typically used for generating keys. #[inline] pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; N] { use rand::RngCore; let mut bytes = [0; N]; rand::rngs::OsRng.fill_bytes(&mut bytes); bytes } /// A wrapper type to store the encrypted data for sensitive pii domain data types #[derive(Debug, Clone)] pub struct Encryptable<T: Clone> { inner: T, encrypted: Secret<Vec<u8>, EncryptionStrategy>, } impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> { /// constructor function to be used by the encryptor and decryptor to generate the data type pub fn new( masked_data: Secret<T, S>, encrypted_data: Secret<Vec<u8>, EncryptionStrategy>, ) -> Self { Self { inner: masked_data, encrypted: encrypted_data, } } } impl<T: Clone> Encryptable<T> { /// Get the inner data while consuming self #[inline] pub fn into_inner(self) -> T { self.inner } /// Get the reference to inner value #[inline] pub fn get_inner(&self) -> &T { &self.inner } /// Get the inner encrypted data while consuming self #[inline] pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.encrypted } /// Deserialize inner value and return new Encryptable object pub fn deserialize_inner_value<U, F>( self, f: F, ) -> CustomResult<Encryptable<U>, errors::ParsingError> where F: FnOnce(T) -> CustomResult<U, errors::ParsingError>, U: Clone, { let inner = self.inner; let encrypted = self.encrypted; let inner = f(inner)?; Ok(Encryptable { inner, encrypted }) } /// consume self and modify the inner value pub fn map<U: Clone>(self, f: impl FnOnce(T) -> U) -> Encryptable<U> { let encrypted_data = self.encrypted; let masked_data = f(self.inner); Encryptable { inner: masked_data, encrypted: encrypted_data, } } } impl<T: Clone> Deref for Encryptable<Secret<T>> { type Target = Secret<T>; fn deref(&self) -> &Self::Target { &self.inner } } impl<T: Clone> masking::Serialize for Encryptable<T> where T: masking::Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.inner.serialize(serializer) } } impl<T: Clone> PartialEq for Encryptable<T> where T: PartialEq, { fn eq(&self, other: &Self) -> bool { self.inner.eq(&other.inner) } } /// Type alias for `Option<Encryptable<Secret<String>>>` pub type OptionalEncryptableSecretString = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `name` field pub type OptionalEncryptableName = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `email` field pub type OptionalEncryptableEmail = Option<Encryptable<Secret<String, pii::EmailStrategy>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `phone` field pub type OptionalEncryptablePhone = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<serde_json::Value>>>` pub type OptionalEncryptableValue = Option<Encryptable<Secret<serde_json::Value>>>; /// Type alias for `Option<Secret<serde_json::Value>>` pub type OptionalSecretValue = Option<Secret<serde_json::Value>>; /// Type alias for `Encryptable<Secret<String>>` used for `name` field pub type EncryptableName = Encryptable<Secret<String>>; /// Type alias for `Encryptable<Secret<String>>` used for `email` field pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>; /// Represents the RSA-PSS-SHA256 signing algorithm #[derive(Debug)] pub struct RsaPssSha256; impl SignMessage for RsaPssSha256 { fn sign_message( &self, private_key_pem_bytes: &[u8], msg_to_sign: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let parsed_pem = pem::parse(private_key_pem_bytes) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to parse PEM string")?; let key_pair = match parsed_pem.tag() { "PRIVATE KEY" => RsaKeyPair::from_pkcs8(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength) .attach_printable("Failed to parse PKCS#8 DER with ring"), "RSA PRIVATE KEY" => RsaKeyPair::from_der(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength) .attach_printable("Failed to parse PKCS#1 DER (using from_der) with ring"), tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'", )), }?; let rng = ring_rand::SystemRandom::new(); let signature_len = key_pair.public().modulus_len(); let mut signature_bytes = vec![0; signature_len]; key_pair .sign(&RSA_PSS_SHA256, &rng, msg_to_sign, &mut signature_bytes) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to sign data with ring")?; Ok(signature_bytes) } } #[cfg(test)] mod crypto_tests { #![allow(clippy::expect_used)] use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature}; use crate::crypto::GenerateDigest; #[test] fn test_hmac_sha256_sign_message() { let message = r#"{"type":"payment_intent"}"#.as_bytes(); let secret = "hmac_secret_1234".as_bytes(); let right_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e") .expect("Right signature decoding"); let signature = super::HmacSha256 .sign_message(secret, message) .expect("Signature"); assert_eq!(signature, right_signature); } #[test] fn test_hmac_sha256_verify_signature() { let right_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e") .expect("Right signature decoding"); let wrong_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f") .expect("Wrong signature decoding"); let secret = "hmac_secret_1234".as_bytes(); let data = r#"{"type":"payment_intent"}"#.as_bytes(); let right_verified = super::HmacSha256 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::HmacSha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_sha256_verify_signature() { let right_signature = hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddba") .expect("Right signature decoding"); let wrong_signature = hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddbb") .expect("Wrong signature decoding"); let secret = "".as_bytes(); let data = r#"AJHFH9349JASFJHADJ9834115USD2020-11-13.13:22:34711000000021406655APPROVED12345product_id"#.as_bytes(); let right_verified = super::Sha256 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::Sha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_hmac_sha512_sign_message() { let message = r#"{"type":"payment_intent"}"#.as_bytes(); let secret = "hmac_secret_1234".as_bytes(); let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f") .expect("signature decoding"); let signature = super::HmacSha512 .sign_message(secret, message) .expect("Signature"); assert_eq!(signature, right_signature); } #[test] fn test_hmac_sha512_verify_signature() { let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f") .expect("signature decoding"); let wrong_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f") .expect("Wrong signature decoding"); let secret = "hmac_secret_1234".as_bytes(); let data = r#"{"type":"payment_intent"}"#.as_bytes(); let right_verified = super::HmacSha512 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::HmacSha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_gcm_aes_256_encode_message() { let message = r#"{"type":"PAYMENT"}"#.as_bytes(); let secret = hex::decode("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") .expect("Secret decoding"); let algorithm = super::GcmAes256; let encoded_message = algorithm .encode_message(&secret, message) .expect("Encoded message and tag"); assert_eq!( algorithm .decode_message(&secret, encoded_message.into()) .expect("Decode Failed"), message ); } #[test] fn test_gcm_aes_256_decode_message() { // Inputs taken from AES GCM test vectors provided by NIST // https://github.com/briansmith/ring/blob/95948b3977013aed16db92ae32e6b8384496a740/tests/aead_aes_256_gcm_tests.txt#L447-L452 let right_secret = hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308") .expect("Secret decoding"); let wrong_secret = hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308309") .expect("Secret decoding"); let message = // The three parts of the message are the nonce, ciphertext and tag from the test vector hex::decode( "cafebabefacedbaddecaf888\ 522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad\ b094dac5d93471bdec1a502270e3cc6c" ).expect("Message decoding"); let algorithm = super::GcmAes256; let decoded = algorithm .decode_message(&right_secret, message.clone().into()) .expect("Decoded message"); assert_eq!( decoded, hex::decode("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255") .expect("Decoded plaintext message") ); let err_decoded = algorithm.decode_message(&wrong_secret, message.into()); assert!(err_decoded.is_err()); } #[test] fn test_md5_digest() { let message = "abcdefghijklmnopqrstuvwxyz".as_bytes(); assert_eq!( format!( "{}", hex::encode(super::Md5.generate_digest(message).expect("Digest")) ), "c3fcd3d76192e4007dfb496cca67e13b" ); } #[test] fn test_md5_verify_signature() { let right_signature = hex::decode("c3fcd3d76192e4007dfb496cca67e13b").expect("signature decoding"); let wrong_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f") .expect("Wrong signature decoding"); let secret = "".as_bytes(); let data = "abcdefghijklmnopqrstuvwxyz".as_bytes(); let right_verified = super::Md5 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::Md5 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } use ring::signature::{UnparsedPublicKey, RSA_PSS_2048_8192_SHA256}; #[test] fn test_rsa_pss_sha256_verify_signature() { let signer = crate::crypto::RsaPssSha256; let message = b"abcdefghijklmnopqrstuvwxyz"; let private_key_pem_bytes = std::fs::read("../../private_key.pem").expect("Failed to read private key"); let parsed_pem = pem::parse(&private_key_pem_bytes).expect("Failed to parse PEM"); let private_key_der = parsed_pem.contents(); let signature = signer .sign_message(&private_key_pem_bytes, message) .expect("Signing failed"); let key_pair = crate::crypto::RsaKeyPair::from_pkcs8(private_key_der) .expect("Failed to parse DER key"); let public_key_der = key_pair.public().as_ref().to_vec(); let public_key = UnparsedPublicKey::new(&RSA_PSS_2048_8192_SHA256, &public_key_der); assert!( public_key.verify(message, &signature).is_ok(), "Right signature should verify" ); let mut wrong_signature = signature.clone(); if let Some(byte) = wrong_signature.first_mut() { *byte ^= 0xFF; } assert!( public_key.verify(message, &wrong_signature).is_err(), "Wrong signature should not verify" ); } #[test] fn test_rsasha256_verify_signature() { use base64::Engine; use rand::rngs::OsRng; use rsa::{ pkcs8::EncodePublicKey, signature::{RandomizedSigner, SignatureEncoding}, }; use crate::consts::BASE64_ENGINE; let mut rng = OsRng; let bits = 2048; let private_key = rsa::RsaPrivateKey::new(&mut rng, bits).expect("keygen failed"); let signing_key = rsa::pkcs1v15::SigningKey::<rsa::sha2::Sha256>::new(private_key.clone()); let message = "{ This is a test message :) }".as_bytes(); let signature = signing_key.sign_with_rng(&mut rng, message); let encoded_signature = BASE64_ENGINE.encode(signature.to_bytes()); let rsa_public_key = private_key.to_public_key(); let pem_format_public_key = rsa_public_key .to_public_key_pem(rsa::pkcs8::LineEnding::LF) .expect("transformation failed"); let encoded_pub_key = BASE64_ENGINE.encode(&pem_format_public_key[..]); let right_verified = super::RsaSha256 .verify_signature( encoded_pub_key.as_bytes(), encoded_signature.as_bytes(), message, ) .expect("Right signature verification result"); assert!(right_verified); } }
crates/common_utils/src/crypto.rs
common_utils::src::crypto
9,411
true
// File: crates/common_utils/src/custom_serde.rs // Module: common_utils::src::custom_serde //! Custom serialization/deserialization implementations. /// Use the well-known ISO 8601 format when serializing and deserializing an /// [`PrimitiveDateTime`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod iso8601 { use std::num::NonZeroU8; use serde::{ser::Error as _, Deserializer, Serialize, Serializer}; use time::{ format_description::well_known::{ iso8601::{Config, EncodedConfig, TimePrecision}, Iso8601, }, serde::iso8601, PrimitiveDateTime, UtcOffset, }; const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT .set_time_precision(TimePrecision::Second { decimal_digits: NonZeroU8::new(3), }) .encode(); /// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format. pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .assume_utc() .format(&Iso8601::<FORMAT_CONFIG>) .map_err(S::Error::custom)? .serialize(serializer) } /// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error> where D: Deserializer<'a>, { iso8601::deserialize(deserializer).map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) } /// Use the well-known ISO 8601 format when serializing and deserializing an /// [`Option<PrimitiveDateTime>`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod option { use serde::Serialize; use time::format_description::well_known::Iso8601; use super::*; /// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format. pub fn serialize<S>( date_time: &Option<PrimitiveDateTime>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .map(|date_time| date_time.assume_utc().format(&Iso8601::<FORMAT_CONFIG>)) .transpose() .map_err(S::Error::custom)? .serialize(serializer) } /// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error> where D: Deserializer<'a>, { iso8601::option::deserialize(deserializer).map(|option_offset_date_time| { option_offset_date_time.map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) }) } } /// Use the well-known ISO 8601 format which is without timezone when serializing and deserializing an /// [`Option<PrimitiveDateTime>`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod option_without_timezone { use serde::{de, Deserialize, Serialize}; use time::macros::format_description; use super::*; /// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format which is without timezone. pub fn serialize<S>( date_time: &Option<PrimitiveDateTime>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .map(|date_time| { let format = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]"); date_time.assume_utc().format(format) }) .transpose() .map_err(S::Error::custom)? .serialize(serializer) } /// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error> where D: Deserializer<'a>, { Option::deserialize(deserializer)? .map(|time_string| { let format = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]"); PrimitiveDateTime::parse(time_string, format).map_err(|_| { de::Error::custom(format!( "Failed to parse PrimitiveDateTime from {time_string}" )) }) }) .transpose() } } } /// Use the UNIX timestamp when serializing and deserializing an /// [`PrimitiveDateTime`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod timestamp { use serde::{Deserializer, Serialize, Serializer}; use time::{serde::timestamp, PrimitiveDateTime, UtcOffset}; /// Serialize a [`PrimitiveDateTime`] using UNIX timestamp. pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .assume_utc() .unix_timestamp() .serialize(serializer) } /// Deserialize an [`PrimitiveDateTime`] from UNIX timestamp. pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error> where D: Deserializer<'a>, { timestamp::deserialize(deserializer).map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) } /// Use the UNIX timestamp when serializing and deserializing an /// [`Option<PrimitiveDateTime>`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod option { use serde::Serialize; use super::*; /// Serialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp. pub fn serialize<S>( date_time: &Option<PrimitiveDateTime>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .map(|date_time| date_time.assume_utc().unix_timestamp()) .serialize(serializer) } /// Deserialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp. pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error> where D: Deserializer<'a>, { timestamp::option::deserialize(deserializer).map(|option_offset_date_time| { option_offset_date_time.map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) }) } } } /// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860> pub mod json_string { use serde::{ de::{self, Deserialize, DeserializeOwned, Deserializer}, ser::{self, Serialize, Serializer}, }; /// Serialize a type to json_string format pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error> where T: Serialize, S: Serializer, { let j = serde_json::to_string(value).map_err(ser::Error::custom)?; j.serialize(serializer) } /// Deserialize a string which is in json format pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: DeserializeOwned, D: Deserializer<'de>, { let j = String::deserialize(deserializer)?; serde_json::from_str(&j).map_err(de::Error::custom) } } /// Use a custom ISO 8601 format when serializing and deserializing /// [`PrimitiveDateTime`][PrimitiveDateTime]. /// /// [PrimitiveDateTime]: ::time::PrimitiveDateTime pub mod iso8601custom { use serde::{ser::Error as _, Deserializer, Serialize, Serializer}; use time::{ format_description::well_known::{ iso8601::{Config, EncodedConfig, TimePrecision}, Iso8601, }, serde::iso8601, PrimitiveDateTime, UtcOffset, }; const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT .set_time_precision(TimePrecision::Second { decimal_digits: None, }) .encode(); /// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format. pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { date_time .assume_utc() .format(&Iso8601::<FORMAT_CONFIG>) .map_err(S::Error::custom)? .replace('T', " ") .replace('Z', "") .serialize(serializer) } /// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation. pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error> where D: Deserializer<'a>, { iso8601::deserialize(deserializer).map(|offset_date_time| { let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC); PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time()) }) } } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use serde_json::json; #[test] fn test_leap_second_parse() { #[derive(Serialize, Deserialize)] struct Try { #[serde(with = "crate::custom_serde::iso8601")] f: time::PrimitiveDateTime, } let leap_second_date_time = json!({"f": "2023-12-31T23:59:60.000Z"}); let deser = serde_json::from_value::<Try>(leap_second_date_time); assert!(deser.is_ok()) } }
crates/common_utils/src/custom_serde.rs
common_utils::src::custom_serde
2,360
true
// File: crates/common_utils/src/metrics/utils.rs // Module: common_utils::src::metrics::utils //! metric utility functions use std::time; use router_env::opentelemetry; /// Record the time taken by the future to execute #[inline] pub async fn time_future<F, R>(future: F) -> (R, time::Duration) where F: futures::Future<Output = R>, { let start = time::Instant::now(); let result = future.await; let time_spent = start.elapsed(); (result, time_spent) } /// Record the time taken (in seconds) by the operation for the given context #[inline] pub async fn record_operation_time<F, R>( future: F, metric: &opentelemetry::metrics::Histogram<f64>, key_value: &[opentelemetry::KeyValue], ) -> R where F: futures::Future<Output = R>, { let (result, time) = time_future(future).await; metric.record(time.as_secs_f64(), key_value); result }
crates/common_utils/src/metrics/utils.rs
common_utils::src::metrics::utils
237
true
// File: crates/common_utils/src/types/primitive_wrappers.rs // Module: common_utils::src::types::primitive_wrappers pub(crate) mod bool_wrappers { use serde::{Deserialize, Serialize}; /// Bool that represents if Extended Authorization is Applied or not #[derive( Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct ExtendedAuthorizationAppliedBool(bool); impl From<bool> for ExtendedAuthorizationAppliedBool { fn from(value: bool) -> Self { Self(value) } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Extended Authorization is Requested or not #[derive( Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct RequestExtendedAuthorizationBool(bool); impl From<bool> for RequestExtendedAuthorizationBool { fn from(value: bool) -> Self { Self(value) } } impl RequestExtendedAuthorizationBool { /// returns the inner bool value pub fn is_true(&self) -> bool { self.0 } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } /// Bool that represents if Extended Authorization is always Requested or not #[derive( Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize, )] #[diesel(sql_type = diesel::sql_types::Bool)] pub struct AlwaysRequestExtendedAuthorization(bool); impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for AlwaysRequestExtendedAuthorization where DB: diesel::backend::Backend, bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB> for AlwaysRequestExtendedAuthorization where DB: diesel::backend::Backend, bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { bool::from_sql(value).map(Self) } } }
crates/common_utils/src/types/primitive_wrappers.rs
common_utils::src::types::primitive_wrappers
955
true
// File: crates/common_utils/src/types/user.rs // Module: common_utils::src::types::user /// User related types pub mod core; /// Theme related types pub mod theme; pub use core::*; pub use theme::*;
crates/common_utils/src/types/user.rs
common_utils::src::types::user
49
true
// File: crates/common_utils/src/types/keymanager.rs // Module: common_utils::src::types::keymanager #![allow(missing_docs)] use core::fmt; use base64::Engine; use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret}; #[cfg(feature = "encryption_service")] use router_env::logger; #[cfg(feature = "km_forward_x_request_id")] use router_env::tracing_actix_web::RequestId; use rustc_hash::FxHashMap; use serde::{ de::{self, Unexpected, Visitor}, ser, Deserialize, Deserializer, Serialize, }; use crate::{ consts::BASE64_ENGINE, crypto::Encryptable, encryption::Encryption, errors::{self, CustomResult}, id_type, transformers::{ForeignFrom, ForeignTryFrom}, }; macro_rules! impl_get_tenant_for_request { ($ty:ident) => { impl GetKeymanagerTenant for $ty { fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId { match self.identifier { Identifier::User(_) | Identifier::UserAuth(_) => state.global_tenant_id.clone(), Identifier::Merchant(_) => state.tenant_id.clone(), } } } }; } #[derive(Debug, Clone)] pub struct KeyManagerState { pub tenant_id: id_type::TenantId, pub global_tenant_id: id_type::TenantId, pub enabled: bool, pub url: String, pub client_idle_timeout: Option<u64>, #[cfg(feature = "km_forward_x_request_id")] pub request_id: Option<RequestId>, #[cfg(feature = "keymanager_mtls")] pub ca: Secret<String>, #[cfg(feature = "keymanager_mtls")] pub cert: Secret<String>, pub infra_values: Option<serde_json::Value>, } impl KeyManagerState { pub fn add_confirm_value_in_infra_values( &self, is_confirm_operation: bool, ) -> Option<serde_json::Value> { self.infra_values.clone().map(|mut infra_values| { if is_confirm_operation { infra_values.as_object_mut().map(|obj| { obj.insert( "is_confirm_operation".to_string(), serde_json::Value::Bool(true), ) }); } infra_values }) } } pub trait GetKeymanagerTenant { fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId; } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] #[serde(tag = "data_identifier", content = "key_identifier")] pub enum Identifier { User(String), Merchant(id_type::MerchantId), UserAuth(String), } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] pub struct EncryptionCreateRequest { #[serde(flatten)] pub identifier: Identifier, } #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] pub struct EncryptionTransferRequest { #[serde(flatten)] pub identifier: Identifier, pub key: String, } #[derive(Debug, Deserialize, Serialize)] pub struct DataKeyCreateResponse { #[serde(flatten)] pub identifier: Identifier, pub key_version: String, } #[derive(Serialize, Deserialize, Debug)] pub struct BatchEncryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: DecryptedDataGroup, } impl_get_tenant_for_request!(EncryptionCreateRequest); impl_get_tenant_for_request!(EncryptionTransferRequest); impl_get_tenant_for_request!(BatchEncryptDataRequest); impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest where S: Strategy<Vec<u8>>, { fn from((secret, identifier): (Secret<Vec<u8>, S>, Identifier)) -> Self { Self { identifier, data: DecryptedData(StrongSecret::new(secret.expose())), } } } impl<S> From<(FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)> for BatchEncryptDataRequest where S: Strategy<Vec<u8>>, { fn from((map, identifier): (FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)) -> Self { let group = map .into_iter() .map(|(key, value)| (key, DecryptedData(StrongSecret::new(value.expose())))) .collect(); Self { identifier, data: DecryptedDataGroup(group), } } } impl<S> From<(Secret<String, S>, Identifier)> for EncryptDataRequest where S: Strategy<String>, { fn from((secret, identifier): (Secret<String, S>, Identifier)) -> Self { Self { data: DecryptedData(StrongSecret::new(secret.expose().as_bytes().to_vec())), identifier, } } } impl<S> From<(Secret<serde_json::Value, S>, Identifier)> for EncryptDataRequest where S: Strategy<serde_json::Value>, { fn from((secret, identifier): (Secret<serde_json::Value, S>, Identifier)) -> Self { Self { data: DecryptedData(StrongSecret::new( secret.expose().to_string().as_bytes().to_vec(), )), identifier, } } } impl<S> From<(FxHashMap<String, Secret<serde_json::Value, S>>, Identifier)> for BatchEncryptDataRequest where S: Strategy<serde_json::Value>, { fn from( (map, identifier): (FxHashMap<String, Secret<serde_json::Value, S>>, Identifier), ) -> Self { let group = map .into_iter() .map(|(key, value)| { ( key, DecryptedData(StrongSecret::new( value.expose().to_string().as_bytes().to_vec(), )), ) }) .collect(); Self { data: DecryptedDataGroup(group), identifier, } } } impl<S> From<(FxHashMap<String, Secret<String, S>>, Identifier)> for BatchEncryptDataRequest where S: Strategy<String>, { fn from((map, identifier): (FxHashMap<String, Secret<String, S>>, Identifier)) -> Self { let group = map .into_iter() .map(|(key, value)| { ( key, DecryptedData(StrongSecret::new(value.expose().as_bytes().to_vec())), ) }) .collect(); Self { data: DecryptedDataGroup(group), identifier, } } } #[derive(Serialize, Deserialize, Debug)] pub struct EncryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: DecryptedData, } #[derive(Debug, Serialize, serde::Deserialize)] pub struct DecryptedDataGroup(pub FxHashMap<String, DecryptedData>); #[derive(Debug, Serialize, Deserialize)] pub struct BatchEncryptDataResponse { pub data: EncryptedDataGroup, } #[derive(Debug, Serialize, Deserialize)] pub struct EncryptDataResponse { pub data: EncryptedData, } #[derive(Debug, Serialize, serde::Deserialize)] pub struct EncryptedDataGroup(pub FxHashMap<String, EncryptedData>); #[derive(Debug)] pub struct TransientBatchDecryptDataRequest { pub identifier: Identifier, pub data: FxHashMap<String, StrongSecret<Vec<u8>>>, } #[derive(Debug)] pub struct TransientDecryptDataRequest { pub identifier: Identifier, pub data: StrongSecret<Vec<u8>>, } #[derive(Debug, Serialize, Deserialize)] pub struct BatchDecryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: FxHashMap<String, StrongSecret<String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct DecryptDataRequest { #[serde(flatten)] pub identifier: Identifier, pub data: StrongSecret<String>, } impl_get_tenant_for_request!(EncryptDataRequest); impl_get_tenant_for_request!(TransientBatchDecryptDataRequest); impl_get_tenant_for_request!(TransientDecryptDataRequest); impl_get_tenant_for_request!(BatchDecryptDataRequest); impl_get_tenant_for_request!(DecryptDataRequest); impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)> for FxHashMap<String, Encryptable<Secret<T, S>>> where T: Clone, S: Strategy<T> + Send, { fn foreign_from( (mut masked_data, response): (FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse), ) -> Self { response .data .0 .into_iter() .flat_map(|(k, v)| { masked_data.remove(&k).map(|inner| { ( k, Encryptable::new(inner.clone(), v.data.peek().clone().into()), ) }) }) .collect() } } impl<T, S> ForeignFrom<(Secret<T, S>, EncryptDataResponse)> for Encryptable<Secret<T, S>> where T: Clone, S: Strategy<T> + Send, { fn foreign_from((masked_data, response): (Secret<T, S>, EncryptDataResponse)) -> Self { Self::new(masked_data, response.data.data.peek().clone().into()) } } pub trait DecryptedDataConversion<T: Clone, S: Strategy<T> + Send>: Sized { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError>; } impl<S: Strategy<String> + Send> DecryptedDataConversion<String, S> for Encryptable<Secret<String, S>> { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError> { let string = String::from_utf8(value.clone().inner().peek().clone()).map_err(|_err| { #[cfg(feature = "encryption_service")] logger::error!("Decryption error {:?}", _err); errors::CryptoError::DecodingFailed })?; Ok(Self::new(Secret::new(string), encryption.into_inner())) } } impl<S: Strategy<serde_json::Value> + Send> DecryptedDataConversion<serde_json::Value, S> for Encryptable<Secret<serde_json::Value, S>> { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError> { let val = serde_json::from_slice(value.clone().inner().peek()).map_err(|_err| { #[cfg(feature = "encryption_service")] logger::error!("Decryption error {:?}", _err); errors::CryptoError::DecodingFailed })?; Ok(Self::new(Secret::new(val), encryption.clone().into_inner())) } } impl<S: Strategy<Vec<u8>> + Send> DecryptedDataConversion<Vec<u8>, S> for Encryptable<Secret<Vec<u8>, S>> { fn convert( value: &DecryptedData, encryption: Encryption, ) -> CustomResult<Self, errors::CryptoError> { Ok(Self::new( Secret::new(value.clone().inner().peek().clone()), encryption.clone().into_inner(), )) } } impl<T, S> ForeignTryFrom<(Encryption, DecryptDataResponse)> for Encryptable<Secret<T, S>> where T: Clone, S: Strategy<T> + Send, Self: DecryptedDataConversion<T, S>, { type Error = error_stack::Report<errors::CryptoError>; fn foreign_try_from( (encrypted_data, response): (Encryption, DecryptDataResponse), ) -> Result<Self, Self::Error> { Self::convert(&response.data, encrypted_data) } } impl<T, S> ForeignTryFrom<(FxHashMap<String, Encryption>, BatchDecryptDataResponse)> for FxHashMap<String, Encryptable<Secret<T, S>>> where T: Clone, S: Strategy<T> + Send, Encryptable<Secret<T, S>>: DecryptedDataConversion<T, S>, { type Error = error_stack::Report<errors::CryptoError>; fn foreign_try_from( (mut encrypted_data, response): (FxHashMap<String, Encryption>, BatchDecryptDataResponse), ) -> Result<Self, Self::Error> { response .data .0 .into_iter() .map(|(k, v)| match encrypted_data.remove(&k) { Some(encrypted) => Ok((k.clone(), Encryptable::convert(&v, encrypted.clone())?)), None => Err(errors::CryptoError::DecodingFailed)?, }) .collect() } } impl From<(Encryption, Identifier)> for TransientDecryptDataRequest { fn from((encryption, identifier): (Encryption, Identifier)) -> Self { Self { data: StrongSecret::new(encryption.clone().into_inner().expose()), identifier, } } } impl From<(FxHashMap<String, Encryption>, Identifier)> for TransientBatchDecryptDataRequest { fn from((map, identifier): (FxHashMap<String, Encryption>, Identifier)) -> Self { let data = map .into_iter() .map(|(k, v)| (k, StrongSecret::new(v.clone().into_inner().expose()))) .collect(); Self { data, identifier } } } #[derive(Debug, Serialize, Deserialize)] pub struct BatchDecryptDataResponse { pub data: DecryptedDataGroup, } #[derive(Debug, Serialize, Deserialize)] pub struct DecryptDataResponse { pub data: DecryptedData, } #[derive(Clone, Debug)] pub struct DecryptedData(StrongSecret<Vec<u8>>); impl Serialize for DecryptedData { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let data = BASE64_ENGINE.encode(self.0.peek()); serializer.serialize_str(&data) } } impl<'de> Deserialize<'de> for DecryptedData { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct DecryptedDataVisitor; impl Visitor<'_> for DecryptedDataVisitor { type Value = DecryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("string of the format {version}:{base64_encoded_data}'") } fn visit_str<E>(self, value: &str) -> Result<DecryptedData, E> where E: de::Error, { let dec_data = BASE64_ENGINE.decode(value).map_err(|err| { let err = err.to_string(); E::invalid_value(Unexpected::Str(value), &err.as_str()) })?; Ok(DecryptedData(dec_data.into())) } } deserializer.deserialize_str(DecryptedDataVisitor) } } impl DecryptedData { pub fn from_data(data: StrongSecret<Vec<u8>>) -> Self { Self(data) } pub fn inner(self) -> StrongSecret<Vec<u8>> { self.0 } } #[derive(Debug)] pub struct EncryptedData { pub data: StrongSecret<Vec<u8>>, } impl Serialize for EncryptedData { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let data = String::from_utf8(self.data.peek().clone()).map_err(ser::Error::custom)?; serializer.serialize_str(data.as_str()) } } impl<'de> Deserialize<'de> for EncryptedData { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct EncryptedDataVisitor; impl Visitor<'_> for EncryptedDataVisitor { type Value = EncryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("string of the format {version}:{base64_encoded_data}'") } fn visit_str<E>(self, value: &str) -> Result<EncryptedData, E> where E: de::Error, { Ok(EncryptedData { data: StrongSecret::new(value.as_bytes().to_vec()), }) } } deserializer.deserialize_str(EncryptedDataVisitor) } } /// A trait which converts the struct to Hashmap required for encryption and back to struct pub trait ToEncryptable<T, S: Clone, E>: Sized { /// Serializes the type to a hashmap fn to_encryptable(self) -> FxHashMap<String, E>; /// Deserializes the hashmap back to the type fn from_encryptable( hashmap: FxHashMap<String, Encryptable<S>>, ) -> CustomResult<T, errors::ParsingError>; }
crates/common_utils/src/types/keymanager.rs
common_utils::src::types::keymanager
3,668
true
// File: crates/common_utils/src/types/authentication.rs // Module: common_utils::src::types::authentication use crate::id_type; /// Enum for different levels of authentication #[derive( Clone, Debug, Hash, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] pub enum AuthInfo { /// OrgLevel: Authentication at the organization level OrgLevel { /// org_id: OrganizationId org_id: id_type::OrganizationId, }, /// MerchantLevel: Authentication at the merchant level MerchantLevel { /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_ids: Vec<MerchantId> merchant_ids: Vec<id_type::MerchantId>, }, /// ProfileLevel: Authentication at the profile level ProfileLevel { /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId merchant_id: id_type::MerchantId, /// profile_ids: Vec<ProfileId> profile_ids: Vec<id_type::ProfileId>, }, } /// Enum for different resource types supported in client secret #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ResourceId { /// Global Payment ID (Not exposed in api_models version of enum) Payment(id_type::GlobalPaymentId), /// Global Customer ID Customer(id_type::GlobalCustomerId), /// Global Payment Methods Session ID PaymentMethodSession(id_type::GlobalPaymentMethodSessionId), } #[cfg(feature = "v2")] impl ResourceId { /// Get string representation of enclosed ID type pub fn to_str(&self) -> &str { match self { Self::Payment(id) => id.get_string_repr(), Self::Customer(id) => id.get_string_repr(), Self::PaymentMethodSession(id) => id.get_string_repr(), } } }
crates/common_utils/src/types/authentication.rs
common_utils::src::types::authentication
444
true
// File: crates/common_utils/src/types/user/core.rs // Module: common_utils::src::types::user::core use diesel::{deserialize::FromSqlRow, expression::AsExpression}; use crate::id_type; /// Struct for lineageContext #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression, FromSqlRow)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct LineageContext { /// user_id: String pub user_id: String, /// merchant_id: MerchantId pub merchant_id: id_type::MerchantId, /// role_id: String pub role_id: String, /// org_id: OrganizationId pub org_id: id_type::OrganizationId, /// profile_id: ProfileId pub profile_id: id_type::ProfileId, /// tenant_id: TenantId pub tenant_id: id_type::TenantId, } crate::impl_to_sql_from_sql_json!(LineageContext);
crates/common_utils/src/types/user/core.rs
common_utils::src::types::user::core
211
true
// File: crates/common_utils/src/types/user/theme.rs // Module: common_utils::src::types::user::theme use common_enums::EntityType; use serde::{Deserialize, Serialize}; use crate::{ events::{ApiEventMetric, ApiEventsType}, id_type, impl_api_event_type, }; /// Enum for having all the required lineage for every level. /// Currently being used for theme related APIs and queries. #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(tag = "entity_type", rename_all = "snake_case")] pub enum ThemeLineage { /// Tenant lineage variant Tenant { /// tenant_id: TenantId tenant_id: id_type::TenantId, }, /// Org lineage variant Organization { /// tenant_id: TenantId tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, }, /// Merchant lineage variant Merchant { /// tenant_id: TenantId tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId merchant_id: id_type::MerchantId, }, /// Profile lineage variant Profile { /// tenant_id: TenantId tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId merchant_id: id_type::MerchantId, /// profile_id: ProfileId profile_id: id_type::ProfileId, }, } impl_api_event_type!(Miscellaneous, (ThemeLineage)); impl ThemeLineage { /// Constructor for ThemeLineage pub fn new( entity_type: EntityType, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, ) -> Self { match entity_type { EntityType::Tenant => Self::Tenant { tenant_id }, EntityType::Organization => Self::Organization { tenant_id, org_id }, EntityType::Merchant => Self::Merchant { tenant_id, org_id, merchant_id, }, EntityType::Profile => Self::Profile { tenant_id, org_id, merchant_id, profile_id, }, } } /// Get the entity_type from the lineage pub fn entity_type(&self) -> EntityType { match self { Self::Tenant { .. } => EntityType::Tenant, Self::Organization { .. } => EntityType::Organization, Self::Merchant { .. } => EntityType::Merchant, Self::Profile { .. } => EntityType::Profile, } } /// Get the tenant_id from the lineage pub fn tenant_id(&self) -> &id_type::TenantId { match self { Self::Tenant { tenant_id } | Self::Organization { tenant_id, .. } | Self::Merchant { tenant_id, .. } | Self::Profile { tenant_id, .. } => tenant_id, } } /// Get the org_id from the lineage pub fn org_id(&self) -> Option<&id_type::OrganizationId> { match self { Self::Tenant { .. } => None, Self::Organization { org_id, .. } | Self::Merchant { org_id, .. } | Self::Profile { org_id, .. } => Some(org_id), } } /// Get the merchant_id from the lineage pub fn merchant_id(&self) -> Option<&id_type::MerchantId> { match self { Self::Tenant { .. } | Self::Organization { .. } => None, Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => { Some(merchant_id) } } } /// Get the profile_id from the lineage pub fn profile_id(&self) -> Option<&id_type::ProfileId> { match self { Self::Tenant { .. } | Self::Organization { .. } | Self::Merchant { .. } => None, Self::Profile { profile_id, .. } => Some(profile_id), } } /// Get higher lineages from the current lineage pub fn get_same_and_higher_lineages(self) -> Vec<Self> { match &self { Self::Tenant { .. } => vec![self], Self::Organization { tenant_id, .. } => vec![ Self::Tenant { tenant_id: tenant_id.clone(), }, self, ], Self::Merchant { tenant_id, org_id, .. } => vec![ Self::Tenant { tenant_id: tenant_id.clone(), }, Self::Organization { tenant_id: tenant_id.clone(), org_id: org_id.clone(), }, self, ], Self::Profile { tenant_id, org_id, merchant_id, .. } => vec![ Self::Tenant { tenant_id: tenant_id.clone(), }, Self::Organization { tenant_id: tenant_id.clone(), org_id: org_id.clone(), }, Self::Merchant { tenant_id: tenant_id.clone(), org_id: org_id.clone(), merchant_id: merchant_id.clone(), }, self, ], } } } /// Struct for holding the theme settings for email #[derive(Debug, Clone, Default, Deserialize, Serialize)] pub struct EmailThemeConfig { /// The entity name to be used in the email pub entity_name: String, /// The URL of the entity logo to be used in the email pub entity_logo_url: String, /// The primary color to be used in the email pub primary_color: String, /// The foreground color to be used in the email pub foreground_color: String, /// The background color to be used in the email pub background_color: String, }
crates/common_utils/src/types/user/theme.rs
common_utils::src::types::user::theme
1,280
true
// File: crates/common_utils/src/id_type/refunds.rs // Module: common_utils::src::id_type::refunds crate::id_type!(RefundReferenceId, "A type for refund_reference_id"); crate::impl_id_type_methods!(RefundReferenceId, "refund_reference_id"); // This is to display the `RefundReferenceId` as RefundReferenceId(abcd) crate::impl_debug_id_type!(RefundReferenceId); crate::impl_try_from_cow_str_id_type!(RefundReferenceId, "refund_reference_id"); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(RefundReferenceId); crate::impl_to_sql_from_sql_id_type!(RefundReferenceId);
crates/common_utils/src/id_type/refunds.rs
common_utils::src::id_type::refunds
160
true
// File: crates/common_utils/src/id_type/organization.rs // Module: common_utils::src::id_type::organization use crate::errors::{CustomResult, ValidationError}; crate::id_type!( OrganizationId, "A type for organization_id that can be used for organization ids" ); crate::impl_id_type_methods!(OrganizationId, "organization_id"); // This is to display the `OrganizationId` as OrganizationId(abcd) crate::impl_debug_id_type!(OrganizationId); crate::impl_default_id_type!(OrganizationId, "org"); crate::impl_try_from_cow_str_id_type!(OrganizationId, "organization_id"); crate::impl_generate_id_id_type!(OrganizationId, "org"); crate::impl_serializable_secret_id_type!(OrganizationId); crate::impl_queryable_id_type!(OrganizationId); crate::impl_to_sql_from_sql_id_type!(OrganizationId); impl OrganizationId { /// Get an organization id from String pub fn try_from_string(org_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(org_id)) } }
crates/common_utils/src/id_type/organization.rs
common_utils::src::id_type::organization
232
true
// File: crates/common_utils/src/id_type/payout.rs // Module: common_utils::src::id_type::payout crate::id_type!( PayoutId, "A domain type for payout_id that can be used for payout ids" ); crate::impl_id_type_methods!(PayoutId, "payout_id"); crate::impl_debug_id_type!(PayoutId); crate::impl_try_from_cow_str_id_type!(PayoutId, "payout_id"); crate::impl_generate_id_id_type!(PayoutId, "payout"); crate::impl_queryable_id_type!(PayoutId); crate::impl_to_sql_from_sql_id_type!(PayoutId);
crates/common_utils/src/id_type/payout.rs
common_utils::src::id_type::payout
143
true
// File: crates/common_utils/src/id_type/profile.rs // Module: common_utils::src::id_type::profile use std::str::FromStr; crate::id_type!( ProfileId, "A type for profile_id that can be used for business profile ids" ); crate::impl_id_type_methods!(ProfileId, "profile_id"); // This is to display the `ProfileId` as ProfileId(abcd) crate::impl_debug_id_type!(ProfileId); crate::impl_try_from_cow_str_id_type!(ProfileId, "profile_id"); crate::impl_generate_id_id_type!(ProfileId, "pro"); crate::impl_serializable_secret_id_type!(ProfileId); crate::impl_queryable_id_type!(ProfileId); crate::impl_to_sql_from_sql_id_type!(ProfileId); impl crate::events::ApiEventMetric for ProfileId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::BusinessProfile { profile_id: self.clone(), }) } } impl FromStr for ProfileId { type Err = error_stack::Report<crate::errors::ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } } // This is implemented so that we can use profile id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<ProfileId> for router_env::opentelemetry::Value { fn from(val: ProfileId) -> Self { Self::from(val.0 .0 .0) } }
crates/common_utils/src/id_type/profile.rs
common_utils::src::id_type::profile
359
true
// File: crates/common_utils/src/id_type/tenant.rs // Module: common_utils::src::id_type::tenant use crate::{ consts::DEFAULT_GLOBAL_TENANT_ID, errors::{CustomResult, ValidationError}, }; crate::id_type!( TenantId, "A type for tenant_id that can be used for unique identifier for a tenant" ); crate::impl_id_type_methods!(TenantId, "tenant_id"); // This is to display the `TenantId` as TenantId(abcd) crate::impl_debug_id_type!(TenantId); crate::impl_try_from_cow_str_id_type!(TenantId, "tenant_id"); crate::impl_serializable_secret_id_type!(TenantId); crate::impl_queryable_id_type!(TenantId); crate::impl_to_sql_from_sql_id_type!(TenantId); impl TenantId { /// Get the default global tenant ID pub fn get_default_global_tenant_id() -> Self { Self(super::LengthId::new_unchecked( super::AlphaNumericId::new_unchecked(DEFAULT_GLOBAL_TENANT_ID.to_string()), )) } /// Get tenant id from String pub fn try_from_string(tenant_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(tenant_id)) } }
crates/common_utils/src/id_type/tenant.rs
common_utils::src::id_type::tenant
277
true
// File: crates/common_utils/src/id_type/merchant_connector_account.rs // Module: common_utils::src::id_type::merchant_connector_account use std::str::FromStr; use crate::errors::{CustomResult, ValidationError}; crate::id_type!( MerchantConnectorAccountId, "A type for merchant_connector_id that can be used for merchant_connector_account ids" ); crate::impl_id_type_methods!(MerchantConnectorAccountId, "merchant_connector_id"); // This is to display the `MerchantConnectorAccountId` as MerchantConnectorAccountId(abcd) crate::impl_debug_id_type!(MerchantConnectorAccountId); crate::impl_generate_id_id_type!(MerchantConnectorAccountId, "mca"); crate::impl_try_from_cow_str_id_type!(MerchantConnectorAccountId, "merchant_connector_id"); crate::impl_serializable_secret_id_type!(MerchantConnectorAccountId); crate::impl_queryable_id_type!(MerchantConnectorAccountId); crate::impl_to_sql_from_sql_id_type!(MerchantConnectorAccountId); impl MerchantConnectorAccountId { /// Get a merchant connector account id from String pub fn wrap(merchant_connector_account_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(merchant_connector_account_id)) } } impl FromStr for MerchantConnectorAccountId { type Err = std::fmt::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::try_from(std::borrow::Cow::Owned(s.to_string())).map_err(|_| std::fmt::Error) } }
crates/common_utils/src/id_type/merchant_connector_account.rs
common_utils::src::id_type::merchant_connector_account
319
true
// File: crates/common_utils/src/id_type/client_secret.rs // Module: common_utils::src::id_type::client_secret crate::id_type!( ClientSecretId, "A type for key_id that can be used for Ephemeral key IDs" ); crate::impl_id_type_methods!(ClientSecretId, "key_id"); // This is to display the `ClientSecretId` as ClientSecretId(abcd) crate::impl_debug_id_type!(ClientSecretId); crate::impl_try_from_cow_str_id_type!(ClientSecretId, "key_id"); crate::impl_generate_id_id_type!(ClientSecretId, "csi"); crate::impl_serializable_secret_id_type!(ClientSecretId); crate::impl_queryable_id_type!(ClientSecretId); crate::impl_to_sql_from_sql_id_type!(ClientSecretId); #[cfg(feature = "v2")] impl crate::events::ApiEventMetric for ClientSecretId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ClientSecret { key_id: self.clone(), }) } } crate::impl_default_id_type!(ClientSecretId, "key"); impl ClientSecretId { /// Generate a key for redis pub fn generate_redis_key(&self) -> String { format!("cs_{}", self.get_string_repr()) } }
crates/common_utils/src/id_type/client_secret.rs
common_utils::src::id_type::client_secret
293
true
// File: crates/common_utils/src/id_type/global_id.rs // Module: common_utils::src::id_type::global_id pub(super) mod customer; pub(super) mod payment; pub(super) mod payment_methods; pub(super) mod refunds; pub(super) mod token; use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types}; use error_stack::ResultExt; use thiserror::Error; use crate::{ consts::{CELL_IDENTIFIER_LENGTH, MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH}, errors, generate_time_ordered_id, id_type::{AlphaNumericId, AlphaNumericIdError, LengthId, LengthIdError}, }; #[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)] /// A global id that can be used to identify any entity /// This id will have information about the entity and cell in a distributed system architecture pub(crate) struct GlobalId(LengthId<MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH>); #[derive(Clone, Copy)] /// Entities that can be identified by a global id pub(crate) enum GlobalEntity { Customer, Payment, Attempt, PaymentMethod, Refund, PaymentMethodSession, Token, } impl GlobalEntity { fn prefix(self) -> &'static str { match self { Self::Customer => "cus", Self::Payment => "pay", Self::PaymentMethod => "pm", Self::Attempt => "att", Self::Refund => "ref", Self::PaymentMethodSession => "pms", Self::Token => "tok", } } } /// Cell identifier for an instance / deployment of application #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct CellId(LengthId<CELL_IDENTIFIER_LENGTH, CELL_IDENTIFIER_LENGTH>); #[derive(Debug, Error, PartialEq, Eq)] pub enum CellIdError { #[error("cell id error: {0}")] InvalidCellLength(LengthIdError), #[error("{0}")] InvalidCellIdFormat(AlphaNumericIdError), } impl From<LengthIdError> for CellIdError { fn from(error: LengthIdError) -> Self { Self::InvalidCellLength(error) } } impl From<AlphaNumericIdError> for CellIdError { fn from(error: AlphaNumericIdError) -> Self { Self::InvalidCellIdFormat(error) } } impl CellId { /// Create a new cell id from a string fn from_str(cell_id_string: impl AsRef<str>) -> Result<Self, CellIdError> { let trimmed_input_string = cell_id_string.as_ref().trim().to_string(); let alphanumeric_id = AlphaNumericId::from(trimmed_input_string.into())?; let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?; Ok(Self(length_id)) } /// Create a new cell id from a string pub fn from_string( input_string: impl AsRef<str>, ) -> error_stack::Result<Self, errors::ValidationError> { Self::from_str(input_string).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "cell_id", }, ) } /// Get the string representation of the cell id fn get_string_repr(&self) -> &str { &self.0 .0 .0 } } impl<'de> serde::Deserialize<'de> for CellId { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from_str(deserialized_string.as_str()).map_err(serde::de::Error::custom) } } /// Error generated from violation of constraints for MerchantReferenceId #[derive(Debug, Error, PartialEq, Eq)] pub(crate) enum GlobalIdError { /// The format for the global id is invalid #[error("The id format is invalid, expected format is {{cell_id:5}}_{{entity_prefix:3}}_{{uuid:32}}_{{random:24}}")] InvalidIdFormat, /// LengthIdError and AlphanumericIdError #[error("{0}")] LengthIdError(#[from] LengthIdError), /// CellIdError because of invalid cell id format #[error("{0}")] CellIdError(#[from] CellIdError), } impl GlobalId { /// Create a new global id from entity and cell information /// The entity prefix is used to identify the entity, `cus` for customers, `pay`` for payments etc. pub fn generate(cell_id: &CellId, entity: GlobalEntity) -> Self { let prefix = format!("{}_{}", cell_id.get_string_repr(), entity.prefix()); let id = generate_time_ordered_id(&prefix); let alphanumeric_id = AlphaNumericId::new_unchecked(id); Self(LengthId::new_unchecked(alphanumeric_id)) } pub(crate) fn from_string( input_string: std::borrow::Cow<'static, str>, ) -> Result<Self, GlobalIdError> { let length_id = LengthId::from(input_string)?; let input_string = &length_id.0 .0; let (cell_id, _remaining) = input_string .split_once("_") .ok_or(GlobalIdError::InvalidIdFormat)?; CellId::from_str(cell_id)?; Ok(Self(length_id)) } pub(crate) fn get_string_repr(&self) -> &str { &self.0 .0 .0 } } impl<DB> ToSql<sql_types::Text, DB> for GlobalId where DB: Backend, String: ToSql<sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0 .0 .0.to_sql(out) } } impl<DB> FromSql<sql_types::Text, DB> for GlobalId where DB: Backend, String: FromSql<sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let string_val = String::from_sql(value)?; let alphanumeric_id = AlphaNumericId::from(string_val.into())?; let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?; Ok(Self(length_id)) } } /// Deserialize the global id from string /// The format should match {cell_id:5}_{entity_prefix:3}_{time_ordered_id:32}_{.*:24} impl<'de> serde::Deserialize<'de> for GlobalId { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let deserialized_string = String::deserialize(deserializer)?; Self::from_string(deserialized_string.into()).map_err(serde::de::Error::custom) } } #[cfg(test)] mod global_id_tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_cell_id_from_str() { let cell_id_string = "12345"; let cell_id = CellId::from_str(cell_id_string).unwrap(); assert_eq!(cell_id.get_string_repr(), cell_id_string); } #[test] fn test_global_id_generate() { let cell_id_string = "12345"; let entity = GlobalEntity::Customer; let cell_id = CellId::from_str(cell_id_string).unwrap(); let global_id = GlobalId::generate(&cell_id, entity); // Generate a regex for globalid // Eg - 12abc_cus_abcdefghijklmnopqrstuvwxyz1234567890 let regex = regex::Regex::new(r"[a-z0-9]{5}_cus_[a-z0-9]{32}").unwrap(); assert!(regex.is_match(&global_id.0 .0 .0)); } #[test] fn test_global_id_from_string() { let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890"; let global_id = GlobalId::from_string(input_string.into()).unwrap(); assert_eq!(global_id.0 .0 .0, input_string); } #[test] fn test_global_id_deser() { let input_string_for_serde_json_conversion = r#""12345_cus_abcdefghijklmnopqrstuvwxyz1234567890""#; let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890"; let global_id = serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion).unwrap(); assert_eq!(global_id.0 .0 .0, input_string); } #[test] fn test_global_id_deser_error() { let input_string_for_serde_json_conversion = r#""123_45_cus_abcdefghijklmnopqrstuvwxyz1234567890""#; let global_id = serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion); assert!(global_id.is_err()); let expected_error_message = format!( "cell id error: the minimum required length for this field is {CELL_IDENTIFIER_LENGTH}" ); let error_message = global_id.unwrap_err().to_string(); assert_eq!(error_message, expected_error_message); } }
crates/common_utils/src/id_type/global_id.rs
common_utils::src::id_type::global_id
2,077
true
// File: crates/common_utils/src/id_type/subscription.rs // Module: common_utils::src::id_type::subscription crate::id_type!( SubscriptionId, " A type for subscription_id that can be used for subscription ids" ); crate::impl_id_type_methods!(SubscriptionId, "subscription_id"); // This is to display the `SubscriptionId` as SubscriptionId(subs) crate::impl_debug_id_type!(SubscriptionId); crate::impl_try_from_cow_str_id_type!(SubscriptionId, "subscription_id"); crate::impl_generate_id_id_type!(SubscriptionId, "sub"); crate::impl_serializable_secret_id_type!(SubscriptionId); crate::impl_queryable_id_type!(SubscriptionId); crate::impl_to_sql_from_sql_id_type!(SubscriptionId); impl crate::events::ApiEventMetric for SubscriptionId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Subscription) } }
crates/common_utils/src/id_type/subscription.rs
common_utils::src::id_type::subscription
207
true
// File: crates/common_utils/src/id_type/merchant.rs // Module: common_utils::src::id_type::merchant //! Contains the id type for merchant account //! //! Ids for merchant account are derived from the merchant name //! If there are any special characters, they are removed use std::fmt::Display; use crate::{ date_time, errors::{CustomResult, ValidationError}, generate_id_with_default_len, id_type::{AlphaNumericId, LengthId}, new_type::MerchantName, types::keymanager, }; crate::id_type!( MerchantId, "A type for merchant_id that can be used for merchant ids" ); crate::impl_id_type_methods!(MerchantId, "merchant_id"); // This is to display the `MerchantId` as MerchantId(abcd) crate::impl_debug_id_type!(MerchantId); crate::impl_default_id_type!(MerchantId, "mer"); crate::impl_try_from_cow_str_id_type!(MerchantId, "merchant_id"); crate::impl_generate_id_id_type!(MerchantId, "mer"); crate::impl_serializable_secret_id_type!(MerchantId); crate::impl_queryable_id_type!(MerchantId); crate::impl_to_sql_from_sql_id_type!(MerchantId); // This is implemented so that we can use merchant id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<MerchantId> for router_env::opentelemetry::Value { fn from(val: MerchantId) -> Self { Self::from(val.0 .0 .0) } } impl MerchantId { /// Create a Merchant id from MerchantName pub fn from_merchant_name(merchant_name: MerchantName) -> Self { let merchant_name_string = merchant_name.into_inner(); let merchant_id_prefix = merchant_name_string.trim().to_lowercase().replace(' ', ""); let alphanumeric_id = AlphaNumericId::new_unchecked(generate_id_with_default_len(&merchant_id_prefix)); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id with the const value of `MERCHANT_ID_NOT_FOUND` pub fn get_merchant_id_not_found() -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked("MERCHANT_ID_NOT_FOUND".to_string()); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id for internal use only pub fn get_internal_user_merchant_id(merchant_id: &str) -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id.to_string()); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Create a new merchant_id from unix timestamp, of the format `merchant_{timestamp}` pub fn new_from_unix_timestamp() -> Self { let merchant_id = format!("merchant_{}", date_time::now_unix_timestamp()); let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id with a value of `irrelevant_merchant_id` pub fn get_irrelevant_merchant_id() -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked("irrelevant_merchant_id".to_string()); let length_id = LengthId::new_unchecked(alphanumeric_id); Self(length_id) } /// Get a merchant id from String pub fn wrap(merchant_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(merchant_id)) } } impl From<MerchantId> for keymanager::Identifier { fn from(value: MerchantId) -> Self { Self::Merchant(value) } } /// All the keys that can be formed from merchant id impl MerchantId { /// get step up enabled key pub fn get_step_up_enabled_key(&self) -> String { format!("step_up_enabled_{}", self.get_string_repr()) } /// get_max_auto_retries_enabled key pub fn get_max_auto_retries_enabled(&self) -> String { format!("max_auto_retries_enabled_{}", self.get_string_repr()) } /// get_requires_cvv_key pub fn get_requires_cvv_key(&self) -> String { format!("{}_requires_cvv", self.get_string_repr()) } /// get_pm_filters_cgraph_key pub fn get_pm_filters_cgraph_key(&self) -> String { format!("pm_filters_cgraph_{}", self.get_string_repr()) } /// get_blocklist_enabled_key pub fn get_blocklist_guard_key(&self) -> String { format!("guard_blocklist_for_{}", self.get_string_repr()) } /// get_merchant_fingerprint_secret_key pub fn get_merchant_fingerprint_secret_key(&self) -> String { format!("fingerprint_secret_{}", self.get_string_repr()) } /// get_surcharge_dsk_key pub fn get_surcharge_dsk_key(&self) -> String { format!("surcharge_dsl_{}", self.get_string_repr()) } /// get_dsk_key pub fn get_dsl_config(&self) -> String { format!("dsl_{}", self.get_string_repr()) } /// get_creds_identifier_key pub fn get_creds_identifier_key(&self, creds_identifier: &str) -> String { format!("mcd_{}_{creds_identifier}", self.get_string_repr()) } /// get_poll_id pub fn get_poll_id(&self, unique_id: &str) -> String { format!("poll_{}_{unique_id}", self.get_string_repr()) } /// get_access_token_key pub fn get_access_token_key( &self, merchant_connector_id_or_connector_name: impl Display, ) -> String { format!( "access_token_{}_{merchant_connector_id_or_connector_name}", self.get_string_repr() ) } /// get_skip_saving_wallet_at_connector_key pub fn get_skip_saving_wallet_at_connector_key(&self) -> String { format!("skip_saving_wallet_at_connector_{}", self.get_string_repr()) } /// get_payment_config_routing_id pub fn get_payment_config_routing_id(&self) -> String { format!("payment_config_id_{}", self.get_string_repr()) } /// get_payment_method_surcharge_routing_id pub fn get_payment_method_surcharge_routing_id(&self) -> String { format!("payment_method_surcharge_id_{}", self.get_string_repr()) } /// get_webhook_config_disabled_events_key pub fn get_webhook_config_disabled_events_key(&self, connector_id: &str) -> String { format!( "whconf_disabled_events_{}_{connector_id}", self.get_string_repr() ) } /// get_should_call_gsm_payout_key pub fn get_should_call_gsm_payout_key( &self, payout_retry_type: common_enums::PayoutRetryType, ) -> String { match payout_retry_type { common_enums::PayoutRetryType::SingleConnector => format!( "should_call_gsm_single_connector_payout_{}", self.get_string_repr() ), common_enums::PayoutRetryType::MultiConnector => format!( "should_call_gsm_multiple_connector_payout_{}", self.get_string_repr() ), } } /// Get should call gsm key for payment pub fn get_should_call_gsm_key(&self) -> String { format!("should_call_gsm_{}", self.get_string_repr()) } /// get_max_auto_single_connector_payout_retries_enabled_ pub fn get_max_auto_single_connector_payout_retries_enabled( &self, payout_retry_type: common_enums::PayoutRetryType, ) -> String { match payout_retry_type { common_enums::PayoutRetryType::SingleConnector => format!( "max_auto_single_connector_payout_retries_enabled_{}", self.get_string_repr() ), common_enums::PayoutRetryType::MultiConnector => format!( "max_auto_multiple_connector_payout_retries_enabled_{}", self.get_string_repr() ), } } /// allow payment update via client auth default should be false pub fn get_payment_update_enabled_for_client_auth_key(&self) -> String { format!( "payment_update_enabled_for_client_auth_{}", self.get_string_repr() ) } }
crates/common_utils/src/id_type/merchant.rs
common_utils::src::id_type::merchant
1,830
true
// File: crates/common_utils/src/id_type/payment.rs // Module: common_utils::src::id_type::payment use crate::{ errors::{CustomResult, ValidationError}, generate_id_with_default_len, id_type::{AlphaNumericId, LengthId}, }; crate::id_type!( PaymentId, "A type for payment_id that can be used for payment ids" ); crate::impl_id_type_methods!(PaymentId, "payment_id"); // This is to display the `PaymentId` as PaymentId(abcd) crate::impl_debug_id_type!(PaymentId); crate::impl_default_id_type!(PaymentId, "pay"); crate::impl_try_from_cow_str_id_type!(PaymentId, "payment_id"); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(PaymentId); crate::impl_to_sql_from_sql_id_type!(PaymentId); impl PaymentId { /// Get the hash key to be stored in redis pub fn get_hash_key_for_kv_store(&self) -> String { format!("pi_{}", self.0 .0 .0) } // This function should be removed once we have a better way to handle mandatory payment id in other flows /// Get payment id in the format of irrelevant_payment_id_in_{flow} pub fn get_irrelevant_id(flow: &str) -> Self { let alphanumeric_id = AlphaNumericId::new_unchecked(format!("irrelevant_payment_id_in_{flow}")); let id = LengthId::new_unchecked(alphanumeric_id); Self(id) } /// Get the attempt id for the payment id based on the attempt count pub fn get_attempt_id(&self, attempt_count: i16) -> String { format!("{}_{attempt_count}", self.get_string_repr()) } /// Generate a client id for the payment id pub fn generate_client_secret(&self) -> String { generate_id_with_default_len(&format!("{}_secret", self.get_string_repr())) } /// Generate a key for pm_auth pub fn get_pm_auth_key(&self) -> String { format!("pm_auth_{}", self.get_string_repr()) } /// Get external authentication request poll id pub fn get_external_authentication_request_poll_id(&self) -> String { format!("external_authentication_{}", self.get_string_repr()) } /// Generate a test payment id with prefix test_ pub fn generate_test_payment_id_for_sample_data() -> Self { let id = generate_id_with_default_len("test"); let alphanumeric_id = AlphaNumericId::new_unchecked(id); let id = LengthId::new_unchecked(alphanumeric_id); Self(id) } /// Wrap a string inside PaymentId pub fn wrap(payment_id_string: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(payment_id_string)) } } crate::id_type!(PaymentReferenceId, "A type for payment_reference_id"); crate::impl_id_type_methods!(PaymentReferenceId, "payment_reference_id"); // This is to display the `PaymentReferenceId` as PaymentReferenceId(abcd) crate::impl_debug_id_type!(PaymentReferenceId); crate::impl_try_from_cow_str_id_type!(PaymentReferenceId, "payment_reference_id"); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(PaymentReferenceId); crate::impl_to_sql_from_sql_id_type!(PaymentReferenceId); // This is implemented so that we can use payment id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<PaymentId> for router_env::opentelemetry::Value { fn from(val: PaymentId) -> Self { Self::from(val.0 .0 .0) } } impl std::str::FromStr for PaymentReferenceId { type Err = error_stack::Report<ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } }
crates/common_utils/src/id_type/payment.rs
common_utils::src::id_type::payment
879
true
// File: crates/common_utils/src/id_type/invoice.rs // Module: common_utils::src::id_type::invoice crate::id_type!( InvoiceId, " A type for invoice_id that can be used for invoice ids" ); crate::impl_id_type_methods!(InvoiceId, "invoice_id"); // This is to display the `InvoiceId` as InvoiceId(subs) crate::impl_debug_id_type!(InvoiceId); crate::impl_try_from_cow_str_id_type!(InvoiceId, "invoice_id"); crate::impl_generate_id_id_type!(InvoiceId, "invoice"); crate::impl_serializable_secret_id_type!(InvoiceId); crate::impl_queryable_id_type!(InvoiceId); crate::impl_to_sql_from_sql_id_type!(InvoiceId); impl crate::events::ApiEventMetric for InvoiceId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Invoice) } }
crates/common_utils/src/id_type/invoice.rs
common_utils::src::id_type::invoice
207
true
// File: crates/common_utils/src/id_type/customer.rs // Module: common_utils::src::id_type::customer crate::id_type!( CustomerId, "A type for customer_id that can be used for customer ids" ); crate::impl_id_type_methods!(CustomerId, "customer_id"); // This is to display the `CustomerId` as CustomerId(abcd) crate::impl_debug_id_type!(CustomerId); crate::impl_default_id_type!(CustomerId, "cus"); crate::impl_try_from_cow_str_id_type!(CustomerId, "customer_id"); crate::impl_generate_id_id_type!(CustomerId, "cus"); crate::impl_serializable_secret_id_type!(CustomerId); crate::impl_queryable_id_type!(CustomerId); crate::impl_to_sql_from_sql_id_type!(CustomerId); #[cfg(feature = "v1")] impl crate::events::ApiEventMetric for CustomerId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Customer { customer_id: self.clone(), }) } }
crates/common_utils/src/id_type/customer.rs
common_utils::src::id_type::customer
227
true
// File: crates/common_utils/src/id_type/profile_acquirer.rs // Module: common_utils::src::id_type::profile_acquirer use std::str::FromStr; crate::id_type!( ProfileAcquirerId, "A type for profile_acquirer_id that can be used for profile acquirer ids" ); crate::impl_id_type_methods!(ProfileAcquirerId, "profile_acquirer_id"); // This is to display the `ProfileAcquirerId` as ProfileAcquirerId(abcd) crate::impl_debug_id_type!(ProfileAcquirerId); crate::impl_try_from_cow_str_id_type!(ProfileAcquirerId, "profile_acquirer_id"); crate::impl_generate_id_id_type!(ProfileAcquirerId, "pro_acq"); crate::impl_serializable_secret_id_type!(ProfileAcquirerId); crate::impl_queryable_id_type!(ProfileAcquirerId); crate::impl_to_sql_from_sql_id_type!(ProfileAcquirerId); impl Ord for ProfileAcquirerId { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0 .0 .0.cmp(&other.0 .0 .0) } } impl PartialOrd for ProfileAcquirerId { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl crate::events::ApiEventMetric for ProfileAcquirerId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ProfileAcquirer { profile_acquirer_id: self.clone(), }) } } impl FromStr for ProfileAcquirerId { type Err = error_stack::Report<crate::errors::ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } } // This is implemented so that we can use profile acquirer id directly as attribute in metrics #[cfg(feature = "metrics")] impl From<ProfileAcquirerId> for router_env::opentelemetry::Value { fn from(val: ProfileAcquirerId) -> Self { Self::from(val.0 .0 .0) } }
crates/common_utils/src/id_type/profile_acquirer.rs
common_utils::src::id_type::profile_acquirer
495
true
// File: crates/common_utils/src/id_type/authentication.rs // Module: common_utils::src::id_type::authentication crate::id_type!( AuthenticationId, "A type for authentication_id that can be used for authentication IDs" ); crate::impl_id_type_methods!(AuthenticationId, "authentication_id"); // This is to display the `AuthenticationId` as AuthenticationId(abcd) crate::impl_debug_id_type!(AuthenticationId); crate::impl_try_from_cow_str_id_type!(AuthenticationId, "authentication_id"); crate::impl_serializable_secret_id_type!(AuthenticationId); crate::impl_queryable_id_type!(AuthenticationId); crate::impl_to_sql_from_sql_id_type!(AuthenticationId); impl AuthenticationId { /// Generate Authentication Id from prefix pub fn generate_authentication_id(prefix: &'static str) -> Self { Self(crate::generate_ref_id_with_default_length(prefix)) } /// Get external authentication request poll id pub fn get_external_authentication_request_poll_id(&self) -> String { format!("external_authentication_{}", self.get_string_repr()) } } impl crate::events::ApiEventMetric for AuthenticationId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Authentication { authentication_id: self.clone(), }) } } impl crate::events::ApiEventMetric for (super::MerchantId, AuthenticationId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Authentication { authentication_id: self.1.clone(), }) } } impl crate::events::ApiEventMetric for (&super::MerchantId, &AuthenticationId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Authentication { authentication_id: self.1.clone(), }) } } crate::impl_default_id_type!(AuthenticationId, "authentication");
crates/common_utils/src/id_type/authentication.rs
common_utils::src::id_type::authentication
427
true
// File: crates/common_utils/src/id_type/routing.rs // Module: common_utils::src::id_type::routing crate::id_type!( RoutingId, " A type for routing_id that can be used for routing ids" ); crate::impl_id_type_methods!(RoutingId, "routing_id"); // This is to display the `RoutingId` as RoutingId(abcd) crate::impl_debug_id_type!(RoutingId); crate::impl_try_from_cow_str_id_type!(RoutingId, "routing_id"); crate::impl_generate_id_id_type!(RoutingId, "routing"); crate::impl_serializable_secret_id_type!(RoutingId); crate::impl_queryable_id_type!(RoutingId); crate::impl_to_sql_from_sql_id_type!(RoutingId); impl crate::events::ApiEventMetric for RoutingId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Routing) } }
crates/common_utils/src/id_type/routing.rs
common_utils::src::id_type::routing
207
true
// File: crates/common_utils/src/id_type/api_key.rs // Module: common_utils::src::id_type::api_key crate::id_type!( ApiKeyId, "A type for key_id that can be used for API key IDs" ); crate::impl_id_type_methods!(ApiKeyId, "key_id"); // This is to display the `ApiKeyId` as ApiKeyId(abcd) crate::impl_debug_id_type!(ApiKeyId); crate::impl_try_from_cow_str_id_type!(ApiKeyId, "key_id"); crate::impl_serializable_secret_id_type!(ApiKeyId); crate::impl_queryable_id_type!(ApiKeyId); crate::impl_to_sql_from_sql_id_type!(ApiKeyId); impl ApiKeyId { /// Generate Api Key Id from prefix pub fn generate_key_id(prefix: &'static str) -> Self { Self(crate::generate_ref_id_with_default_length(prefix)) } } impl crate::events::ApiEventMetric for ApiKeyId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ApiKey { key_id: self.clone(), }) } } impl crate::events::ApiEventMetric for (super::MerchantId, ApiKeyId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ApiKey { key_id: self.1.clone(), }) } } impl crate::events::ApiEventMetric for (&super::MerchantId, &ApiKeyId) { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::ApiKey { key_id: self.1.clone(), }) } } crate::impl_default_id_type!(ApiKeyId, "key");
crates/common_utils/src/id_type/api_key.rs
common_utils::src::id_type::api_key
393
true
// File: crates/common_utils/src/id_type/relay.rs // Module: common_utils::src::id_type::relay use std::str::FromStr; crate::id_type!( RelayId, "A type for relay_id that can be used for relay ids" ); crate::impl_id_type_methods!(RelayId, "relay_id"); crate::impl_try_from_cow_str_id_type!(RelayId, "relay_id"); crate::impl_generate_id_id_type!(RelayId, "relay"); crate::impl_serializable_secret_id_type!(RelayId); crate::impl_queryable_id_type!(RelayId); crate::impl_to_sql_from_sql_id_type!(RelayId); crate::impl_debug_id_type!(RelayId); impl FromStr for RelayId { type Err = error_stack::Report<crate::errors::ValidationError>; fn from_str(s: &str) -> Result<Self, Self::Err> { let cow_string = std::borrow::Cow::Owned(s.to_string()); Self::try_from(cow_string) } }
crates/common_utils/src/id_type/relay.rs
common_utils::src::id_type::relay
226
true
// File: crates/common_utils/src/id_type/webhook_endpoint.rs // Module: common_utils::src::id_type::webhook_endpoint use crate::errors::{CustomResult, ValidationError}; crate::id_type!( WebhookEndpointId, "A type for webhook_endpoint_id that can be used for unique identifier for a webhook_endpoint" ); crate::impl_id_type_methods!(WebhookEndpointId, "webhook_endpoint_id"); crate::impl_generate_id_id_type!(WebhookEndpointId, "whe"); crate::impl_default_id_type!(WebhookEndpointId, "whe"); // This is to display the `WebhookEndpointId` as WebhookEndpointId(abcd) crate::impl_debug_id_type!(WebhookEndpointId); crate::impl_try_from_cow_str_id_type!(WebhookEndpointId, "webhook_endpoint_id"); crate::impl_serializable_secret_id_type!(WebhookEndpointId); crate::impl_queryable_id_type!(WebhookEndpointId); crate::impl_to_sql_from_sql_id_type!(WebhookEndpointId); impl WebhookEndpointId { /// Get webhook_endpoint id from String pub fn try_from_string(webhook_endpoint_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(webhook_endpoint_id)) } }
crates/common_utils/src/id_type/webhook_endpoint.rs
common_utils::src::id_type::webhook_endpoint
274
true
// File: crates/common_utils/src/id_type/global_id/payment_methods.rs // Module: common_utils::src::id_type::global_id::payment_methods use error_stack::ResultExt; use crate::{ errors::CustomResult, id_type::global_id::{CellId, GlobalEntity, GlobalId}, }; /// A global id that can be used to identify a payment method #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct GlobalPaymentMethodId(GlobalId); /// A global id that can be used to identify a payment method session #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct GlobalPaymentMethodSessionId(GlobalId); #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum GlobalPaymentMethodIdError { #[error("Failed to construct GlobalPaymentMethodId")] ConstructionError, } #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum GlobalPaymentMethodSessionIdError { #[error("Failed to construct GlobalPaymentMethodSessionId")] ConstructionError, } impl GlobalPaymentMethodSessionId { /// Create a new GlobalPaymentMethodSessionId from cell id information pub fn generate( cell_id: &CellId, ) -> error_stack::Result<Self, GlobalPaymentMethodSessionIdError> { let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethodSession); Ok(Self(global_id)) } /// Get the string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Construct a redis key from the id to be stored in redis pub fn get_redis_key(&self) -> String { format!("payment_method_session:{}", self.get_string_repr()) } } #[cfg(feature = "v2")] impl crate::events::ApiEventMetric for GlobalPaymentMethodSessionId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::PaymentMethodSession { payment_method_session_id: self.clone(), }) } } impl crate::events::ApiEventMetric for GlobalPaymentMethodId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some( crate::events::ApiEventsType::PaymentMethodListForPaymentMethods { payment_method_id: self.clone(), }, ) } } impl GlobalPaymentMethodId { /// Create a new GlobalPaymentMethodId from cell id information pub fn generate(cell_id: &CellId) -> error_stack::Result<Self, GlobalPaymentMethodIdError> { let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod); Ok(Self(global_id)) } /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Construct a new GlobalPaymentMethodId from a string pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> { let id = GlobalId::from_string(value.into()) .change_context(GlobalPaymentMethodIdError::ConstructionError)?; Ok(Self(id)) } } impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodId where DB: diesel::backend::Backend, Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodId where DB: diesel::backend::Backend, GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodId where DB: diesel::backend::Backend, GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let global_id = GlobalId::from_sql(value)?; Ok(Self(global_id)) } } impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId where DB: diesel::backend::Backend, Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId where DB: diesel::backend::Backend, GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId where DB: diesel::backend::Backend, GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let global_id = GlobalId::from_sql(value)?; Ok(Self(global_id)) } }
crates/common_utils/src/id_type/global_id/payment_methods.rs
common_utils::src::id_type::global_id::payment_methods
1,351
true
// File: crates/common_utils/src/id_type/global_id/refunds.rs // Module: common_utils::src::id_type::global_id::refunds use error_stack::ResultExt; use crate::errors; /// A global id that can be used to identify a refund #[derive( Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, diesel::expression::AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] pub struct GlobalRefundId(super::GlobalId); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalRefundId); impl GlobalRefundId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate a new GlobalRefundId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Refund); Self(global_id) } } // TODO: refactor the macro to include this id use case as well impl TryFrom<std::borrow::Cow<'static, str>> for GlobalRefundId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { let merchant_ref_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "refund_id", }, )?; Ok(Self(merchant_ref_id)) } } // TODO: refactor the macro to include this id use case as well impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalRefundId where DB: diesel::backend::Backend, super::GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>, { fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, DB>, ) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalRefundId where DB: diesel::backend::Backend, super::GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>, { fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { super::GlobalId::from_sql(value).map(Self) } }
crates/common_utils/src/id_type/global_id/refunds.rs
common_utils::src::id_type::global_id::refunds
595
true
// File: crates/common_utils/src/id_type/global_id/token.rs // Module: common_utils::src::id_type::global_id::token use std::borrow::Cow; use error_stack::ResultExt; use crate::errors::{CustomResult, ValidationError}; crate::global_id_type!( GlobalTokenId, "A global id that can be used to identify a token. The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. Example: `cell1_tok_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalTokenId); crate::impl_to_sql_from_sql_global_id_type!(GlobalTokenId); impl GlobalTokenId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } ///Get GlobalTokenId from a string pub fn from_string(token_string: &str) -> CustomResult<Self, ValidationError> { let token = super::GlobalId::from_string(Cow::Owned(token_string.to_string())) .change_context(ValidationError::IncorrectValueProvided { field_name: "GlobalTokenId", })?; Ok(Self(token)) } /// Generate a new GlobalTokenId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Token); Self(global_id) } } impl crate::events::ApiEventMetric for GlobalTokenId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Token { token_id: Some(self.clone()), }) } }
crates/common_utils/src/id_type/global_id/token.rs
common_utils::src::id_type::global_id::token
421
true
// File: crates/common_utils/src/id_type/global_id/payment.rs // Module: common_utils::src::id_type::global_id::payment use common_enums::enums; use error_stack::ResultExt; use crate::errors; crate::global_id_type!( GlobalPaymentId, "A global id that can be used to identify a payment. The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. Example: `cell1_pay_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalPaymentId); crate::impl_to_sql_from_sql_global_id_type!(GlobalPaymentId); impl GlobalPaymentId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate a new GlobalPaymentId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Payment); Self(global_id) } /// Generate the id for revenue recovery Execute PT workflow pub fn get_execute_revenue_recovery_id( &self, task: &str, runner: enums::ProcessTrackerRunner, ) -> String { format!("{runner}_{task}_{}", self.get_string_repr()) } /// Generate a key for gift card connector pub fn get_gift_card_connector_key(&self) -> String { format!("gift_mca_{}", self.get_string_repr()) } } // TODO: refactor the macro to include this id use case as well impl TryFrom<std::borrow::Cow<'static, str>> for GlobalPaymentId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { let merchant_ref_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", }, )?; Ok(Self(merchant_ref_id)) } } crate::global_id_type!( GlobalAttemptId, "A global id that can be used to identify a payment attempt" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalAttemptId); crate::impl_to_sql_from_sql_global_id_type!(GlobalAttemptId); impl GlobalAttemptId { /// Generate a new GlobalAttemptId from a cell id pub fn generate(cell_id: &super::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Attempt); Self(global_id) } /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate the id for Revenue Recovery Psync PT workflow pub fn get_psync_revenue_recovery_id( &self, task: &str, runner: enums::ProcessTrackerRunner, ) -> String { format!("{runner}_{task}_{}", self.get_string_repr()) } } impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> { let global_attempt_id = super::GlobalId::from_string(value).change_context( errors::ValidationError::IncorrectValueProvided { field_name: "payment_id", }, )?; Ok(Self(global_attempt_id)) } }
crates/common_utils/src/id_type/global_id/payment.rs
common_utils::src::id_type::global_id::payment
836
true
// File: crates/common_utils/src/id_type/global_id/customer.rs // Module: common_utils::src::id_type::global_id::customer use crate::errors; crate::global_id_type!( GlobalCustomerId, "A global id that can be used to identify a customer. The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. Example: `cell1_cus_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" ); // Database related implementations so that this field can be used directly in the database tables crate::impl_queryable_id_type!(GlobalCustomerId); crate::impl_to_sql_from_sql_global_id_type!(GlobalCustomerId); impl GlobalCustomerId { /// Get string representation of the id pub fn get_string_repr(&self) -> &str { self.0.get_string_repr() } /// Generate a new GlobalCustomerId from a cell id pub fn generate(cell_id: &crate::id_type::CellId) -> Self { let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Customer); Self(global_id) } } impl TryFrom<GlobalCustomerId> for crate::id_type::CustomerId { type Error = error_stack::Report<errors::ValidationError>; fn try_from(value: GlobalCustomerId) -> Result<Self, Self::Error> { Self::try_from(std::borrow::Cow::from(value.get_string_repr().to_owned())) } } impl crate::events::ApiEventMetric for GlobalCustomerId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Customer { customer_id: Some(self.clone()), }) } }
crates/common_utils/src/id_type/global_id/customer.rs
common_utils::src::id_type::global_id::customer
386
true
// File: crates/hyperswitch_domain_models/src/tokenization.rs // Module: hyperswitch_domain_models::src::tokenization use common_enums; use common_utils::{ self, date_time, errors::{CustomResult, ValidationError}, types::keymanager, }; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Tokenization { pub id: common_utils::id_type::GlobalTokenId, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::GlobalCustomerId, pub locker_id: String, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub flag: common_enums::TokenizationFlag, pub version: common_enums::ApiVersion, } impl Tokenization { pub fn is_disabled(&self) -> bool { self.flag == common_enums::TokenizationFlag::Disabled } } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TokenizationNew { pub id: common_utils::id_type::GlobalTokenId, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::GlobalCustomerId, pub locker_id: String, pub flag: common_enums::TokenizationFlag, pub version: common_enums::ApiVersion, } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TokenizationResponse { pub token: String, pub created_at: PrimitiveDateTime, pub flag: common_enums::TokenizationFlag, } impl From<Tokenization> for TokenizationResponse { fn from(value: Tokenization) -> Self { Self { token: value.id.get_string_repr().to_string(), created_at: value.created_at, flag: value.flag, } } } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Serialize, Deserialize)] pub enum TokenizationUpdate { DeleteTokenizationRecordUpdate { flag: Option<common_enums::enums::TokenizationFlag>, }, } #[async_trait::async_trait] impl super::behaviour::Conversion for Tokenization { type DstType = diesel_models::tokenization::Tokenization; type NewDstType = diesel_models::tokenization::Tokenization; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::tokenization::Tokenization { id: self.id, merchant_id: self.merchant_id, customer_id: self.customer_id, locker_id: self.locker_id, created_at: self.created_at, updated_at: self.updated_at, version: self.version, flag: self.flag, }) } async fn convert_back( _state: &keymanager::KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> { Ok(Self { id: item.id, merchant_id: item.merchant_id, customer_id: item.customer_id, locker_id: item.locker_id, created_at: item.created_at, updated_at: item.updated_at, flag: item.flag, version: item.version, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::tokenization::Tokenization { id: self.id, merchant_id: self.merchant_id, customer_id: self.customer_id, locker_id: self.locker_id, created_at: self.created_at, updated_at: self.updated_at, version: self.version, flag: self.flag, }) } } impl From<TokenizationUpdate> for diesel_models::tokenization::TokenizationUpdateInternal { fn from(value: TokenizationUpdate) -> Self { let now = date_time::now(); match value { TokenizationUpdate::DeleteTokenizationRecordUpdate { flag } => Self { updated_at: now, flag, }, } } }
crates/hyperswitch_domain_models/src/tokenization.rs
hyperswitch_domain_models::src::tokenization
949
true