Dataset Viewer
Auto-converted to Parquet
id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
file_storage_impl_-1279733294048394195
clm
file
// Repository: hyperswitch // Crate: storage_impl // File: crates/storage_impl/src/mock_db.rs // Contains: 1 structs, 0 enums 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 {}
{ "crate": "storage_impl", "file": "crates/storage_impl/src/mock_db.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_storage_impl_-885193815745525373
clm
file
// Repository: hyperswitch // Crate: storage_impl // File: crates/storage_impl/src/config.rs // Contains: 1 structs, 1 enums 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() } }
{ "crate": "storage_impl", "file": "crates/storage_impl/src/config.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_storage_impl_-1840274334618533077
clm
file
// Repository: hyperswitch // Crate: storage_impl // File: crates/storage_impl/src/lib.rs // Contains: 1 structs, 0 enums 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" } }
{ "crate": "storage_impl", "file": "crates/storage_impl/src/lib.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_storage_impl_-7221812085936325475
clm
file
// Repository: hyperswitch // Crate: storage_impl // File: crates/storage_impl/src/kv_router_store.rs // Contains: 1 structs, 0 enums 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> {}
{ "crate": "storage_impl", "file": "crates/storage_impl/src/kv_router_store.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_storage_impl_-3094499605474430919
clm
file
// Repository: hyperswitch // Crate: storage_impl // File: crates/storage_impl/src/redis.rs // Contains: 1 structs, 0 enums 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()) } } }
{ "crate": "storage_impl", "file": "crates/storage_impl/src/redis.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_storage_impl_3276040950322020961
clm
file
// Repository: hyperswitch // Crate: storage_impl // File: crates/storage_impl/src/database/store.rs // Contains: 3 structs, 0 enums 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 } }
{ "crate": "storage_impl", "file": "crates/storage_impl/src/database/store.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 3, "num_tables": null, "score": null, "total_crates": null }
file_storage_impl_-7646703352176012178
clm
file
// Repository: hyperswitch // Crate: storage_impl // File: crates/storage_impl/src/redis/cache.rs // Contains: 2 structs, 1 enums 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 ); } }
{ "crate": "storage_impl", "file": "crates/storage_impl/src/redis/cache.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_-6576528134363597775
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/request.rs // Contains: 2 structs, 2 enums 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() } }
{ "crate": "common_utils", "file": "crates/common_utils/src/request.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 2, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_4097855999874423392
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/types.rs // Contains: 19 structs, 3 enums //! 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; }
{ "crate": "common_utils", "file": "crates/common_utils/src/types.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 3, "num_structs": 19, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_187077588499932904
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/encryption.rs // Contains: 1 structs, 0 enums 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 } }
{ "crate": "common_utils", "file": "crates/common_utils/src/encryption.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_752039877199717807
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/lib.rs // Contains: 4 structs, 1 enums #![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;
{ "crate": "common_utils", "file": "crates/common_utils/src/lib.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 1, "num_structs": 4, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_-7622348567784450268
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/new_type.rs // Contains: 8 structs, 0 enums //! 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()); } }
{ "crate": "common_utils", "file": "crates/common_utils/src/new_type.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 8, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_-2975949343650304862
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/signals.rs // Contains: 1 structs, 0 enums //! 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) {} }
{ "crate": "common_utils", "file": "crates/common_utils/src/signals.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_505334816538760746
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/validation.rs // Contains: 1 structs, 0 enums //! 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")); } }
{ "crate": "common_utils", "file": "crates/common_utils/src/validation.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 0, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_-6115316558658704543
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/pii.rs // Contains: 2 structs, 6 enums //! 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:?}")); } }
{ "crate": "common_utils", "file": "crates/common_utils/src/pii.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 6, "num_structs": 2, "num_tables": null, "score": null, "total_crates": null }
file_common_utils_4847919099944751473
clm
file
// Repository: hyperswitch // Crate: common_utils // File: crates/common_utils/src/errors.rs // Contains: 1 structs, 7 enums //! 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) } }
{ "crate": "common_utils", "file": "crates/common_utils/src/errors.rs", "file_size": null, "is_async": null, "is_pub": null, "num_enums": 7, "num_structs": 1, "num_tables": null, "score": null, "total_crates": null }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
15