id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
fn_clm_storage_impl_insert_merchant_key_store_4266589853430521646
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/merchant_key_store // Implementation of MockDb for MerchantKeyStoreInterface async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, Self::Error> { let mut locked_merchant_key_store = self.merchant_key_store.lock().await; if locked_merchant_key_store .iter() .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id) { Err(StorageError::DuplicateValue { entity: "merchant_key_store", key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()), })?; } let merchant_key = Conversion::convert(merchant_key_store) .await .change_context(StorageError::MockDbError)?; locked_merchant_key_store.push(merchant_key.clone()); let merchant_id = merchant_key.merchant_id.clone(); merchant_key .convert(state, key, merchant_id.into()) .await .change_context(StorageError::DecryptionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 55, "total_crates": null }
fn_clm_storage_impl_list_multiple_key_stores_4266589853430521646
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/merchant_key_store // Implementation of MockDb for MerchantKeyStoreInterface async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all( merchant_key_stores .iter() .filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id)) .map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError) }), ) .await }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 33, "total_crates": null }
fn_clm_storage_impl_get_all_key_stores_4266589853430521646
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/merchant_key_store // Implementation of MockDb for MerchantKeyStoreInterface async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, _from: u32, _to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(StorageError::DecryptionError) })) .await }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 32, "total_crates": null }
fn_clm_storage_impl_delete_merchant_key_store_by_merchant_id_4266589853430521646
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/merchant_key_store // Implementation of MockDb for MerchantKeyStoreInterface async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, StorageError> { let mut merchant_key_stores = self.merchant_key_store.lock().await; let index = merchant_key_stores .iter() .position(|mks| mks.merchant_id == *merchant_id) .ok_or(StorageError::ValueNotFound(format!( "No merchant key store found for merchant_id = {merchant_id:?}", )))?; merchant_key_stores.remove(index); Ok(true) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_storage_impl_pg_connection_read_4181215574452794697
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/connection pub async fn pg_connection_read<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::errors::StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_master_pool(); pool.get() .await .change_context(crate::errors::StorageError::DatabaseConnectionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 69, "total_crates": null }
fn_clm_storage_impl_pg_connection_write_4181215574452794697
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/connection pub async fn pg_connection_write<T: crate::DatabaseStore>( store: &T, ) -> errors::CustomResult< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, crate::errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(crate::errors::StorageError::DatabaseConnectionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 37, "total_crates": null }
fn_clm_storage_impl_redis_connection_4181215574452794697
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/connection pub async fn redis_connection( redis: &redis_interface::RedisSettings, ) -> redis_interface::RedisConnectionPool { redis_interface::RedisConnectionPool::new(redis) .await .expect("Failed to create Redis Connection Pool") }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 15, "total_crates": null }
fn_clm_storage_impl_pg_connection_read_-8123943447551112816
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/utils pub async fn pg_connection_read<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] let pool = store.get_replica_pool(); // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. // 2. Both OLAP and OLTP is enabled. // 3. Both OLAP and OLTP is disabled. #[cfg(any( all(not(feature = "olap"), feature = "oltp"), all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] let pool = store.get_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 69, "total_crates": null }
fn_clm_storage_impl_try_redis_get_else_try_database_get_-8123943447551112816
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/utils pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>( redis_fut: RFut, database_call_closure: F, ) -> error_stack::Result<T, StorageError> where F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<T, StorageError>>, { let redis_output = redis_fut.await; match redis_output { Ok(output) => Ok(output), Err(redis_error) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call_closure().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 54, "total_crates": null }
fn_clm_storage_impl_find_all_combined_kv_database_-8123943447551112816
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/utils pub async fn find_all_combined_kv_database<F, RFut, DFut, T>( redis_fut: RFut, database_call: F, limit: Option<i64>, ) -> error_stack::Result<Vec<T>, StorageError> where T: UniqueConstraints, F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<Vec<T>, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<Vec<T>, StorageError>>, { let trunc = |v: &mut Vec<_>| { if let Some(l) = limit.and_then(|v| TryInto::try_into(v).ok()) { v.truncate(l); } }; let limit_satisfies = |len: usize, limit: i64| { TryInto::try_into(limit) .ok() .is_none_or(|val: usize| len >= val) }; let redis_output = redis_fut.await; match (redis_output, limit) { (Ok(mut kv_rows), Some(lim)) if limit_satisfies(kv_rows.len(), lim) => { trunc(&mut kv_rows); Ok(kv_rows) } (Ok(kv_rows), _) => database_call().await.map(|db_rows| { let mut res = union_vec(kv_rows, db_rows); trunc(&mut res); res }), (Err(redis_error), _) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 49, "total_crates": null }
fn_clm_storage_impl_pg_connection_write_-8123943447551112816
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/utils pub async fn pg_connection_write<T: DatabaseStore>( store: &T, ) -> error_stack::Result< PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>, StorageError, > { // Since all writes should happen to master DB only choose master DB. let pool = store.get_master_pool(); pool.get() .await .change_context(StorageError::DatabaseConnectionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 37, "total_crates": null }
fn_clm_storage_impl_union_vec_-8123943447551112816
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/utils fn union_vec<T>(mut kv_rows: Vec<T>, sql_rows: Vec<T>) -> Vec<T> where T: UniqueConstraints, { let mut kv_unique_keys = HashSet::new(); kv_rows.iter().for_each(|v| { kv_unique_keys.insert(v.unique_constraints().concat()); }); sql_rows.into_iter().for_each(|v| { let unique_key = v.unique_constraints().concat(); if !kv_unique_keys.contains(&unique_key) { kv_rows.push(v); } }); kv_rows }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 27, "total_crates": null }
fn_clm_storage_impl_new_-1737113234814815458
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis // Inherent implementation for 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?), }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14467, "total_crates": null }
fn_clm_storage_impl_get_redis_conn_-1737113234814815458
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis // Implementation of RedisStore for RedisConnInterface 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": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 209, "total_crates": null }
fn_clm_storage_impl_fmt_-1737113234814815458
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis // Implementation of RedisStore for std::fmt::Debug 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() }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 44, "total_crates": null }
fn_clm_storage_impl_set_error_callback_-1737113234814815458
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis // Inherent implementation for RedisStore 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(), ); }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 29, "total_crates": null }
fn_clm_storage_impl_new_-6364918330300426834
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/database/store // Implementation of ReplicaStore for DatabaseStore 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, }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14477, "total_crates": null }
fn_clm_storage_impl_diesel_make_pg_pool_-6364918330300426834
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/database/store 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") }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 57, "total_crates": null }
fn_clm_storage_impl_get_master_pool_-6364918330300426834
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/database/store // Implementation of ReplicaStore for DatabaseStore fn get_master_pool(&self) -> &PgPool { &self.master_pool }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 32, "total_crates": null }
fn_clm_storage_impl_get_replica_pool_-6364918330300426834
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/database/store // Implementation of ReplicaStore for DatabaseStore fn get_replica_pool(&self) -> &PgPool { &self.replica_pool }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_storage_impl_get_accounts_master_pool_-6364918330300426834
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/database/store // Implementation of ReplicaStore for DatabaseStore fn get_accounts_master_pool(&self) -> &PgPool { &self.accounts_master_pool }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_storage_impl_update_payment_attempt_with_attempt_id_2548090575559944668
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_attempt // Implementation of KVRouterStore<T> for PaymentAttemptInterface async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let key = PartitionKey::MerchantIdPaymentId { merchant_id: &this.merchant_id, payment_id: &this.payment_id, }; let field = format!("pa_{}", this.attempt_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .update_payment_attempt_with_attempt_id(this, payment_attempt, storage_scheme) .await } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let old_connector_transaction_id = &this.get_connector_payment_id(); let old_preprocessing_id = &this.preprocessing_step_id; let updated_attempt = PaymentAttempt::from_storage_model( payment_attempt .clone() .to_storage_model() .apply_changeset(this.clone().to_storage_model()), ); // Check for database presence as well Maybe use a read replica here ? let redis_value = serde_json::to_string(&updated_attempt) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::PaymentAttemptUpdate(Box::new( kv::PaymentAttemptUpdateMems { orig: this.clone().to_storage_model(), update_data: payment_attempt.to_storage_model(), }, ))), }, }; match ( old_connector_transaction_id, &updated_attempt.get_connector_payment_id(), ) { (None, Some(connector_transaction_id)) => { add_connector_txn_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), connector_transaction_id, storage_scheme, ) .await?; } (Some(old_connector_transaction_id), Some(connector_transaction_id)) => { if old_connector_transaction_id.ne(connector_transaction_id) { add_connector_txn_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), connector_transaction_id, storage_scheme, ) .await?; } } (_, _) => {} } match (old_preprocessing_id, &updated_attempt.preprocessing_step_id) { (None, Some(preprocessing_id)) => { add_preprocessing_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), preprocessing_id.as_str(), storage_scheme, ) .await?; } (Some(old_preprocessing_id), Some(preprocessing_id)) => { if old_preprocessing_id.ne(preprocessing_id) { add_preprocessing_id_to_reverse_lookup( self, key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), preprocessing_id.as_str(), storage_scheme, ) .await?; } } (_, _) => {} } Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<DieselPaymentAttempt>((&field, redis_value), redis_entry), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_attempt) } } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 150, "total_crates": null }
fn_clm_storage_impl_insert_payment_attempt_2548090575559944668
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_attempt // Implementation of KVRouterStore<T> for PaymentAttemptInterface async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, payment_attempt: PaymentAttempt, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Insert, )) .await; match decided_storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .insert_payment_attempt( key_manager_state, merchant_key_store, payment_attempt, decided_storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalPaymentId { id: &payment_attempt.payment_id, }; let key_str = key.to_string(); let field = format!( "{}_{}", label::CLUSTER_LABEL, payment_attempt.id.get_string_repr() ); let diesel_payment_attempt_new = payment_attempt .clone() .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let diesel_payment_attempt_for_redis: DieselPaymentAttempt = Conversion::convert(payment_attempt.clone()) .await .change_context(errors::StorageError::EncryptionError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new( diesel_payment_attempt_new.clone(), ))), }, }; let reverse_lookup_attempt_id = ReverseLookupNew { lookup_id: label::get_global_id_label(&payment_attempt.id), pk_id: key_str.clone(), sk_id: field.clone(), source: "payment_attempt".to_string(), updated_by: decided_storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup_attempt_id, decided_storage_scheme) .await?; if let Some(ref conn_txn_id_val) = payment_attempt.connector_payment_id { let reverse_lookup_conn_txn_id = ReverseLookupNew { lookup_id: label::get_profile_id_connector_transaction_label( payment_attempt.profile_id.get_string_repr(), conn_txn_id_val, ), pk_id: key_str.clone(), sk_id: field.clone(), source: "payment_attempt".to_string(), updated_by: decided_storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup_conn_txn_id, decided_storage_scheme) .await?; } match Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>( self, KvOperation::HSetNx(&field, &diesel_payment_attempt_for_redis, redis_entry), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "payment_attempt", key: Some(payment_attempt.id.get_string_repr().to_owned()), } .into()), Ok(HsetnxReply::KeySet) => Ok(payment_attempt), Err(error) => Err(error.change_context(errors::StorageError::KVError)), } } } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 123, "total_crates": null }
fn_clm_storage_impl_to_storage_model_2548090575559944668
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_attempt // Implementation of PaymentAttemptNew for DataModelExt fn to_storage_model(self) -> Self::StorageModel { DieselPaymentAttemptNew { net_amount: Some(self.net_amount.get_total_amount()), payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.net_amount.get_order_amount(), currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.net_amount.get_surcharge_amount(), tax_amount: self.net_amount.get_tax_on_surcharge(), payment_method_id: self.payment_method_id, payment_method: self.payment_method, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at.unwrap_or_else(common_utils::date_time::now), modified_at: self .modified_at .unwrap_or_else(common_utils::date_time::now), last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, error_code: self.error_code, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, card_network: self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|value| value.as_object()) .and_then(|map| map.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_method_data: self.payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details.map(|d| d.to_storage_model()), error_reason: self.error_reason, connector_response_reference_id: self.connector_response_reference_id, multiple_capture_count: self.multiple_capture_count, amount_capturable: self.amount_capturable, updated_by: self.updated_by, authentication_data: self.authentication_data, encoded_data: self.encoded_data, merchant_connector_id: self.merchant_connector_id, unified_code: self.unified_code, unified_message: self.unified_message, external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data.map(|d| d.to_storage_model()), payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, organization_id: self.organization_id, profile_id: self.profile_id, shipping_cost: self.net_amount.get_shipping_cost(), order_tax_amount: self.net_amount.get_order_tax_amount(), connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|created_by| created_by.to_string()), setup_future_usage_applied: self.setup_future_usage_applied, routing_approach: self.routing_approach, connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 113, "total_crates": null }
fn_clm_storage_impl_find_payment_attempt_by_payment_id_merchant_id_attempt_id_2548090575559944668
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_attempt // Implementation of KVRouterStore<T> for PaymentAttemptInterface async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_id, merchant_id, attempt_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let field = format!("pa_{attempt_id}"); Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&field), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_id, merchant_id, attempt_id, storage_scheme, ) .await }, )) .await } } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 104, "total_crates": null }
fn_clm_storage_impl_find_payment_attempt_by_attempt_id_merchant_id_2548090575559944668
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_attempt // Implementation of KVRouterStore<T> for PaymentAttemptInterface async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { self.router_store .find_payment_attempt_by_attempt_id_merchant_id( attempt_id, merchant_id, storage_scheme, ) .await } MerchantStorageScheme::RedisKv => { let lookup_id = format!("pa_{}_{attempt_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, self.router_store .find_payment_attempt_by_attempt_id_merchant_id( attempt_id, merchant_id, storage_scheme, ) .await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, || async { self.router_store .find_payment_attempt_by_attempt_id_merchant_id( attempt_id, merchant_id, storage_scheme, ) .await }, )) .await } } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 74, "total_crates": null }
fn_clm_storage_impl_get_filtered_payment_intents_attempt_1128400087147478593
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_intent // Implementation of crate::RouterStore<T> for PaymentIntentInterface async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, constraints: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> { use diesel::NullableExpressionMethods as _; use futures::{future::try_join_all, FutureExt}; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .left_join( payment_attempt_schema::table .on(pi_dsl::active_attempt_id.eq(pa_dsl::id.nullable())), ) // Filtering on merchant_id for payment_attempt is not required for v2 as payment_attempt_ids are globally unique .into_boxed(); query = match constraints { PaymentIntentFetchConstraints::List(params) => { query = match params.order { Order { on: SortOn::Amount, by: SortBy::Asc, } => query.order(pi_dsl::amount.asc()), Order { on: SortOn::Amount, by: SortBy::Desc, } => query.order(pi_dsl::amount.desc()), Order { on: SortOn::Created, by: SortBy::Asc, } => query.order(pi_dsl::created_at.asc()), Order { on: SortOn::Created, by: SortBy::Desc, } => query.order(pi_dsl::created_at.desc()), }; if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { query = query.filter( pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()), ) } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_id( state, starting_after_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_id( state, ending_before_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match params.amount_filter { Some(AmountFilter { start_amount: Some(start), end_amount: Some(end), }) => query.filter(pi_dsl::amount.between(start, end)), Some(AmountFilter { start_amount: Some(start), end_amount: None, }) => query.filter(pi_dsl::amount.ge(start)), Some(AmountFilter { start_amount: None, end_amount: Some(end), }) => query.filter(pi_dsl::amount.le(end)), _ => query, }; query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.connector { Some(connector) => query.filter(pa_dsl::connector.eq_any(connector.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; query = match &params.payment_method_type { Some(payment_method_type) => query .filter(pa_dsl::payment_method_type_v2.eq_any(payment_method_type.clone())), None => query, }; query = match &params.payment_method_subtype { Some(payment_method_subtype) => query.filter( pa_dsl::payment_method_subtype.eq_any(payment_method_subtype.clone()), ), None => query, }; query = match &params.authentication_type { Some(authentication_type) => query .filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())), None => query, }; query = match &params.merchant_connector_id { Some(merchant_connector_id) => query.filter( pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()), ), None => query, }; if let Some(card_network) = &params.card_network { query = query.filter(pa_dsl::card_network.eq_any(card_network.clone())); } if let Some(payment_id) = &params.payment_id { query = query.filter(pi_dsl::id.eq(payment_id.clone())); } query } }; logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query .get_results_async::<( DieselPaymentIntent, Option<diesel_models::payment_attempt::PaymentAttempt>, )>(conn) .await .change_context(StorageError::DecryptionError) .async_and_then(|output| async { try_join_all(output.into_iter().map( |(pi, pa): (_, Option<diesel_models::payment_attempt::PaymentAttempt>)| async { let payment_intent = PaymentIntent::convert_back( state, pi, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ); let payment_attempt = pa .async_map(|val| { PaymentAttempt::convert_back( state, val, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) }) .map(|val| val.transpose()); let output = futures::try_join!(payment_intent, payment_attempt); output.change_context(StorageError::DecryptionError) }, )) .await }) .await .change_context(StorageError::DecryptionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 197, "total_crates": null }
fn_clm_storage_impl_find_payment_intent_by_payment_id_merchant_id_1128400087147478593
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_intent // Implementation of crate::RouterStore<T> for PaymentIntentInterface async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .async_and_then(|diesel_payment_intent| async { PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }) .await }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 158, "total_crates": null }
fn_clm_storage_impl_filter_payment_intent_by_constraints_1128400087147478593
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_intent // Implementation of crate::RouterStore<T> for PaymentIntentInterface async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, filters: &PaymentIntentFetchConstraints, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { use futures::{future::try_join_all, FutureExt}; let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); //[#350]: Replace this with Boxable Expression and pass it into generic filter // when https://github.com/rust-lang/rust/issues/52662 becomes stable let mut query = <DieselPaymentIntent as HasTable>::table() .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .order(pi_dsl::created_at.desc()) .into_boxed(); match filters { PaymentIntentFetchConstraints::Single { payment_intent_id } => { query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned())); } PaymentIntentFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match (params.starting_at, &params.starting_after_id) { (Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payment_intent_by_payment_id_merchant_id( state, starting_after_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, &params.ending_before_id) { (Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payment_intent_by_payment_id_merchant_id( state, ending_before_id, merchant_id, merchant_key_store, storage_scheme, ) .await? .created_at; query.filter(pi_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); query = match &params.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; if let Some(currency) = &params.currency { query = query.filter(pi_dsl::currency.eq_any(currency.clone())); } if let Some(status) = &params.status { query = query.filter(pi_dsl::status.eq_any(status.clone())); } } } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>( query.get_results_async::<DieselPaymentIntent>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map(|payment_intents| { try_join_all(payment_intents.into_iter().map(|diesel_payment_intent| { PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payment records"), ) })? .await }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 131, "total_crates": null }
fn_clm_storage_impl_update_payment_intent_1128400087147478593
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_intent // Implementation of crate::RouterStore<T> for PaymentIntentInterface async fn update_payment_intent( &self, state: &KeyManagerState, this: PaymentIntent, payment_intent: PaymentIntentUpdate, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; let diesel_payment_intent_update = PaymentIntentUpdateInternal::try_from(payment_intent) .change_context(StorageError::DeserializationFailed)?; let diesel_payment_intent = this .convert() .await .change_context(StorageError::EncryptionError)? .update(&conn, diesel_payment_intent_update) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(StorageError::DecryptionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 119, "total_crates": null }
fn_clm_storage_impl_find_payment_intent_by_id_1128400087147478593
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payments/payment_intent // Implementation of crate::RouterStore<T> for PaymentIntentInterface async fn find_payment_intent_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_read(self).await?; let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) })?; let merchant_id = diesel_payment_intent.merchant_id.clone(); PaymentIntent::convert_back( state, diesel_payment_intent, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(StorageError::DecryptionError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 95, "total_crates": null }
fn_clm_storage_impl_try_from_5076120225940169030
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/cache // Implementation of CacheRedact<'_> for TryFrom<RedisValue> 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(), }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2669, "total_crates": null }
fn_clm_storage_impl_from_5076120225940169030
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/cache // Implementation of String for From<CacheKey> fn from(val: CacheKey) -> Self { if val.prefix.is_empty() { val.key } else { format!("{}:{}", val.prefix, val.key) } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2602, "total_crates": null }
fn_clm_storage_impl_dact_from_redis_and_publish< _5076120225940169030
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/cache b 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>()) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 46, "total_crates": null }
fn_clm_storage_impl_w( _5076120225940169030
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/cache // Inherent implementation for 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 b 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(), } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 29, "total_crates": null }
fn_clm_storage_impl_t_or_populate_in_memory<T_5076120225940169030
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/cache b 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) } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 28, "total_crates": null }
fn_clm_storage_impl_kv_wrapper_3970462156580834839
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/kv_store pub async fn kv_wrapper<'a, T, D, S>( store: &KVRouterStore<D>, op: KvOperation<'a, S>, partition_key: PartitionKey<'a>, ) -> CustomResult<KvResult<T>, RedisError> where T: de::DeserializeOwned, D: crate::database::store::DatabaseStore, S: serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync, { let redis_conn = store.get_redis_conn()?; let key = format!("{partition_key}"); let type_name = std::any::type_name::<T>(); let operation = op.to_string(); let ttl = store.ttl_for_kv; let result = async { match op { KvOperation::Hset(value, sql) => { logger::debug!(kv_operation= %operation, value = ?value); redis_conn .set_hash_fields(&key.into(), value, Some(ttl.into())) .await?; store .push_to_drainer_stream::<S>(sql, partition_key) .await?; Ok(KvResult::Hset(())) } KvOperation::HGet(field) => { let result = redis_conn .get_hash_field_and_deserialize(&key.into(), field, type_name) .await?; Ok(KvResult::HGet(result)) } KvOperation::Scan(pattern) => { let result: Vec<T> = redis_conn .hscan_and_deserialize(&key.into(), pattern, None) .await .and_then(|result| { if result.is_empty() { Err(report!(RedisError::NotFound)) } else { Ok(result) } })?; Ok(KvResult::Scan(result)) } KvOperation::HSetNx(field, value, sql) => { logger::debug!(kv_operation= %operation, value = ?value); value.check_for_constraints(&redis_conn).await?; let result = redis_conn .serialize_and_set_hash_field_if_not_exist(&key.into(), field, value, Some(ttl)) .await?; if matches!(result, redis_interface::HsetnxReply::KeySet) { store .push_to_drainer_stream::<S>(sql, partition_key) .await?; Ok(KvResult::HSetNx(result)) } else { Err(report!(RedisError::SetNxFailed)) } } KvOperation::SetNx(value, sql) => { logger::debug!(kv_operation= %operation, value = ?value); let result = redis_conn .serialize_and_set_key_if_not_exist(&key.into(), value, Some(ttl.into())) .await?; value.check_for_constraints(&redis_conn).await?; if matches!(result, redis_interface::SetnxReply::KeySet) { store .push_to_drainer_stream::<S>(sql, partition_key) .await?; Ok(KvResult::SetNx(result)) } else { Err(report!(RedisError::SetNxFailed)) } } KvOperation::Get => { let result = redis_conn .get_and_deserialize_key(&key.into(), type_name) .await?; Ok(KvResult::Get(result)) } } }; let attributes = router_env::metric_attributes!(("operation", operation.clone())); result .await .inspect(|_| { logger::debug!(kv_operation= %operation, status="success"); metrics::KV_OPERATION_SUCCESSFUL.add(1, attributes); }) .inspect_err(|err| { logger::error!(kv_operation = %operation, status="error", error = ?err); metrics::KV_OPERATION_FAILED.add(1, attributes); }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 97, "total_crates": null }
fn_clm_storage_impl_fmt_3970462156580834839
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/kv_store // Implementation of Op<'_> for std::fmt::Display fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Op::Insert => f.write_str("insert"), Op::Find => f.write_str("find"), Op::Update(p_key, _, updated_by) => { f.write_str(&format!("update_{p_key} for updated_by_{updated_by:?}")) } } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 44, "total_crates": null }
fn_clm_storage_impl_decide_storage_scheme_3970462156580834839
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/kv_store pub async fn decide_storage_scheme<T, D>( store: &KVRouterStore<T>, storage_scheme: MerchantStorageScheme, operation: Op<'_>, ) -> MerchantStorageScheme where D: de::DeserializeOwned + serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync, T: crate::database::store::DatabaseStore, { if store.soft_kill_mode { let ops = operation.to_string(); let updated_scheme = match operation { Op::Insert => MerchantStorageScheme::PostgresOnly, Op::Find => MerchantStorageScheme::RedisKv, Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly, Op::Update(partition_key, field, Some(_updated_by)) => { match Box::pin(kv_wrapper::<D, _, _>( store, KvOperation::<D>::HGet(field), partition_key, )) .await { Ok(_) => { metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(1, &[]); MerchantStorageScheme::RedisKv } Err(_) => MerchantStorageScheme::PostgresOnly, } } Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly, }; let type_name = std::any::type_name::<D>(); logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme,entity = %type_name, operation = %ops); updated_scheme } else { storage_scheme } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_storage_impl_partition_number_3970462156580834839
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/kv_store fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 { crc32fast::hash(key.to_string().as_bytes()) % u32::from(num_partitions) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 8, "total_crates": null }
fn_clm_storage_impl_shard_key_3970462156580834839
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/kv_store fn shard_key(key: PartitionKey<'_>, num_partitions: u8) -> String { format!("shard_{}", Self::partition_number(key, num_partitions)) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 3, "total_crates": null }
fn_clm_storage_impl_on_message_4726383909084637409
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/pub_sub // Implementation of std::sync::Arc<redis_interface::RedisConnectionPool> for PubSubInterface async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> { logger::debug!("Started on message"); let mut rx = self.subscriber.on_message(); while let Ok(message) = rx.recv().await { let channel_name = message.channel.to_string(); logger::debug!("Received message on channel: {channel_name}"); match channel_name.as_str() { super::cache::IMC_INVALIDATION_CHANNEL => { let message = match CacheRedact::try_from(RedisValue::new(message.value)) .change_context(redis_errors::RedisError::OnMessageError) { Ok(value) => value, Err(err) => { logger::error!(value_conversion_err=?err); continue; } }; let key = match message.kind { CacheKind::Config(key) => { CONFIG_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Accounts(key) => { ACCOUNTS_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::CGraph(key) => { CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::PmFiltersCGraph(key) => { PM_FILTERS_CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::EliminationBasedDynamicRoutingCache(key) => { ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::ContractBasedDynamicRoutingCache(key) => { CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::SuccessBasedDynamicRoutingCache(key) => { SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Routing(key) => { ROUTING_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::DecisionManager(key) => { DECISION_MANAGER_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Surcharge(key) => { SURCHARGE_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::All(key) => { CONFIG_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ACCOUNTS_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; PM_FILTERS_CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ROUTING_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; DECISION_MANAGER_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; SURCHARGE_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } }; logger::debug!( key_prefix=?message.tenant.clone(), channel_name=?channel_name, "Done invalidating {key}" ); } _ => { logger::debug!("Received message from unknown channel: {channel_name}"); } } } Ok(()) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 148, "total_crates": null }
fn_clm_storage_impl_subscribe_4726383909084637409
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/pub_sub // Implementation of std::sync::Arc<redis_interface::RedisConnectionPool> for PubSubInterface async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> { // Spawns a task that will automatically re-subscribe to any channels or channel patterns used by the client. self.subscriber.manage_subscriptions(); self.subscriber .subscribe::<(), &str>(channel) .await .change_context(redis_errors::RedisError::SubscribeError)?; // Spawn only one thread handling all the published messages to different channels if self .subscriber .is_subscriber_handler_spawned .compare_exchange( false, true, atomic::Ordering::SeqCst, atomic::Ordering::SeqCst, ) .is_ok() { let redis_clone = self.clone(); let _task_handle = tokio::spawn( async move { if let Err(pubsub_error) = redis_clone.on_message().await { logger::error!(?pubsub_error); } } .in_current_span(), ); } Ok(()) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 33, "total_crates": null }
fn_clm_storage_impl_publish_4726383909084637409
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/redis/pub_sub // Implementation of std::sync::Arc<redis_interface::RedisConnectionPool> for PubSubInterface async fn publish<'a>( &self, channel: &str, key: CacheKind<'a>, ) -> error_stack::Result<usize, redis_errors::RedisError> { let key = CacheRedact { kind: key, tenant: self.key_prefix.clone(), }; self.publisher .publish( channel, RedisValue::try_from(key).change_context(redis_errors::RedisError::PublishError)?, ) .await .change_context(redis_errors::RedisError::SubscribeError) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_storage_impl_find_payment_attempt_by_payment_id_merchant_id_attempt_id_5202082131702034554
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_attempt // Implementation of MockDb for PaymentAttemptInterface async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, _payment_id: &common_utils::id_type::PaymentId, _merchant_id: &common_utils::id_type::MerchantId, _attempt_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 86, "total_crates": null }
fn_clm_storage_impl_update_payment_attempt_with_attempt_id_5202082131702034554
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_attempt // Implementation of MockDb for PaymentAttemptInterface async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, payment_attempt: PaymentAttemptUpdate, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { let mut payment_attempts = self.payment_attempts.lock().await; let item = payment_attempts .iter_mut() .find(|item| item.attempt_id == this.attempt_id) .unwrap(); *item = PaymentAttempt::from_storage_model( payment_attempt .to_storage_model() .apply_changeset(this.to_storage_model()), ); Ok(item.clone()) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 84, "total_crates": null }
fn_clm_storage_impl_find_payment_attempt_by_attempt_id_merchant_id_5202082131702034554
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_attempt // Implementation of MockDb for PaymentAttemptInterface async fn find_payment_attempt_by_attempt_id_merchant_id( &self, _attempt_id: &str, _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 56, "total_crates": null }
fn_clm_storage_impl_insert_payment_attempt_5202082131702034554
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_attempt // Implementation of MockDb for PaymentAttemptInterface async fn insert_payment_attempt( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, _payment_attempt: PaymentAttempt, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 53, "total_crates": null }
fn_clm_storage_impl_find_payment_attempt_by_id_5202082131702034554
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_attempt // Implementation of MockDb for PaymentAttemptInterface async fn find_payment_attempt_by_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, _attempt_id: &id_type::GlobalAttemptId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 35, "total_crates": null }
fn_clm_storage_impl_update_payout_-1040875852437078251
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payouts // Implementation of MockDb for PayoutsInterface async fn update_payout( &self, _this: &Payouts, _payout_update: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Payouts, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 50, "total_crates": null }
fn_clm_storage_impl_find_payout_by_merchant_id_payout_id_-1040875852437078251
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payouts // Implementation of MockDb for PayoutsInterface async fn find_payout_by_merchant_id_payout_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payout_id: &common_utils::id_type::PayoutId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Payouts, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_storage_impl_filter_payouts_by_constraints_-1040875852437078251
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payouts // Implementation of MockDb for PayoutsInterface async fn filter_payouts_by_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, _filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<Payouts>, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 17, "total_crates": null }
fn_clm_storage_impl_insert_payout_-1040875852437078251
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payouts // Implementation of MockDb for PayoutsInterface async fn insert_payout( &self, _payout: PayoutsNew, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Payouts, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14, "total_crates": null }
fn_clm_storage_impl_find_optional_payout_by_merchant_id_payout_id_-1040875852437078251
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payouts // Implementation of MockDb for PayoutsInterface async fn find_optional_payout_by_merchant_id_payout_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payout_id: &common_utils::id_type::PayoutId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<Payouts>, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14, "total_crates": null }
fn_clm_storage_impl_get_redis_conn_8090586842542804000
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/redis_conn // Implementation of MockDb for RedisConnInterface fn get_redis_conn( &self, ) -> Result<Arc<redis_interface::RedisConnectionPool>, error_stack::Report<RedisError>> { self.redis.get_redis_conn() }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 205, "total_crates": null }
fn_clm_storage_impl_update_payout_attempt_-2490171417103140250
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payout_attempt // Implementation of MockDb for PayoutAttemptInterface async fn update_payout_attempt( &self, _this: &PayoutAttempt, _payout_attempt_update: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 65, "total_crates": null }
fn_clm_storage_impl_find_payout_attempt_by_merchant_id_payout_attempt_id_-2490171417103140250
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payout_attempt // Implementation of MockDb for PayoutAttemptInterface async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payout_attempt_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_storage_impl_insert_payout_attempt_-2490171417103140250
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payout_attempt // Implementation of MockDb for PayoutAttemptInterface async fn insert_payout_attempt( &self, _payout_attempt: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 17, "total_crates": null }
fn_clm_storage_impl_find_payout_attempt_by_merchant_id_connector_payout_id_-2490171417103140250
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payout_attempt // Implementation of MockDb for PayoutAttemptInterface async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _connector_payout_id: &str, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PayoutAttempt, StorageError> { // TODO: Implement function for `MockDb` Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 17, "total_crates": null }
fn_clm_storage_impl_get_filters_for_payouts_-2490171417103140250
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payout_attempt // Implementation of MockDb for PayoutAttemptInterface async fn get_filters_for_payouts( &self, _payouts: &[Payouts], _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters, StorageError, > { Err(StorageError::MockDbError)? }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 17, "total_crates": null }
fn_clm_storage_impl_find_payment_intent_by_payment_id_merchant_id_9028097532822597608
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_intent // Implementation of MockDb for PaymentIntentInterface async fn find_payment_intent_by_payment_id_merchant_id( &self, _state: &KeyManagerState, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; Ok(payment_intents .iter() .find(|payment_intent| { payment_intent.get_id() == payment_id && payment_intent.merchant_id.eq(merchant_id) }) .cloned() .unwrap()) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 146, "total_crates": null }
fn_clm_storage_impl_update_payment_intent_9028097532822597608
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_intent // Implementation of MockDb for PaymentIntentInterface async fn update_payment_intent( &self, _state: &KeyManagerState, _this: PaymentIntent, _update: PaymentIntentUpdate, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { todo!() }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 89, "total_crates": null }
fn_clm_storage_impl_find_payment_intent_by_id_9028097532822597608
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_intent // Implementation of MockDb for PaymentIntentInterface async fn find_payment_intent_by_id( &self, _state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, _merchant_key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter() .find(|payment_intent| payment_intent.get_id() == id) .ok_or(StorageError::ValueNotFound( "PaymentIntent not found".to_string(), ))?; Ok(payment_intent.clone()) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 87, "total_crates": null }
fn_clm_storage_impl_find_payment_intent_by_merchant_reference_id_profile_id_9028097532822597608
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_intent // Implementation of MockDb for PaymentIntentInterface async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, _state: &KeyManagerState, merchant_reference_id: &common_utils::id_type::PaymentReferenceId, profile_id: &common_utils::id_type::ProfileId, _merchant_key_store: &MerchantKeyStore, _storage_scheme: &common_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let payment_intents = self.payment_intents.lock().await; let payment_intent = payment_intents .iter() .find(|payment_intent| { payment_intent.merchant_reference_id.as_ref() == Some(merchant_reference_id) && payment_intent.profile_id.eq(profile_id) }) .ok_or(StorageError::ValueNotFound( "PaymentIntent not found".to_string(), ))?; Ok(payment_intent.clone()) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 32, "total_crates": null }
fn_clm_storage_impl_insert_payment_intent_9028097532822597608
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/mock_db/payment_intent // Implementation of MockDb for PaymentIntentInterface async fn insert_payment_intent( &self, _state: &KeyManagerState, new: PaymentIntent, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { let mut payment_intents = self.payment_intents.lock().await; payment_intents.push(new.clone()); Ok(new) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 23, "total_crates": null }
fn_clm_storage_impl_filter_payouts_by_constraints_-8307965716849434756
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payouts // Implementation of crate::RouterStore<T> for PayoutsInterface async fn filter_payouts_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, filters: &PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); //[#350]: Replace this with Boxable Expression and pass it into generic filter // when https://github.com/rust-lang/rust/issues/52662 becomes stable let mut query = <DieselPayouts as HasTable>::table() .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())) .order(po_dsl::created_at.desc()) .into_boxed(); match filters { PayoutFetchConstraints::Single { payout_id } => { query = query.filter(po_dsl::payout_id.eq(payout_id.to_owned())); } PayoutFetchConstraints::List(params) => { if let Some(limit) = params.limit { query = query.limit(limit.into()); } if let Some(customer_id) = &params.customer_id { query = query.filter(po_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(po_dsl::profile_id.eq(profile_id.clone())); } query = match (params.starting_at, params.starting_after_id.as_ref()) { (Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)), (None, Some(starting_after_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let starting_at = self .find_payout_by_merchant_id_payout_id( merchant_id, starting_after_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.ge(starting_at)) } (None, None) => query, }; query = match (params.ending_at, params.ending_before_id.as_ref()) { (Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)), (None, Some(ending_before_id)) => { // TODO: Fetch partial columns for this query since we only need some columns let ending_at = self .find_payout_by_merchant_id_payout_id( merchant_id, ending_before_id, storage_scheme, ) .await? .created_at; query.filter(po_dsl::created_at.le(ending_at)) } (None, None) => query, }; query = query.offset(params.offset.into()); if let Some(currency) = &params.currency { query = query.filter(po_dsl::destination_currency.eq_any(currency.clone())); } if let Some(status) = &params.status { query = query.filter(po_dsl::status.eq_any(status.clone())); } } } logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>( query.get_results_async::<DieselPayouts>(conn), db_metrics::DatabaseOperation::Filter, ) .await .map(|payouts| { payouts .into_iter() .map(Payouts::from_storage_model) .collect::<Vec<Payouts>>() }) .map_err(|er| { StorageError::DatabaseError( error_stack::report!(diesel_models::errors::DatabaseError::from(er)) .attach_printable("Error filtering payout records"), ) .into() }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 111, "total_crates": null }
fn_clm_storage_impl_update_payout_-8307965716849434756
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payouts // Implementation of crate::RouterStore<T> for PayoutsInterface async fn update_payout( &self, this: &Payouts, payout: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_write(self).await?; this.clone() .to_storage_model() .update(&conn, payout.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(Payouts::from_storage_model) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 70, "total_crates": null }
fn_clm_storage_impl_to_storage_model_-8307965716849434756
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payouts // Implementation of PayoutsUpdate for DataModelExt fn to_storage_model(self) -> Self::StorageModel { match self { Self::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, } => DieselPayoutsUpdate::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, }, Self::PayoutMethodIdUpdate { payout_method_id } => { DieselPayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } } Self::RecurringUpdate { recurring } => { DieselPayoutsUpdate::RecurringUpdate { recurring } } Self::AttemptCountUpdate { attempt_count } => { DieselPayoutsUpdate::AttemptCountUpdate { attempt_count } } Self::StatusUpdate { status } => DieselPayoutsUpdate::StatusUpdate { status }, } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 59, "total_crates": null }
fn_clm_storage_impl_find_payout_by_merchant_id_payout_id_-8307965716849434756
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payouts // Implementation of crate::RouterStore<T> for PayoutsInterface async fn find_payout_by_merchant_id_payout_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, StorageError> { let conn = pg_connection_read(self).await?; DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id) .await .map(Payouts::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 40, "total_crates": null }
fn_clm_storage_impl_get_total_count_of_filtered_payouts_-8307965716849434756
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payouts // Implementation of crate::RouterStore<T> for PayoutsInterface async fn get_total_count_of_filtered_payouts( &self, merchant_id: &common_utils::id_type::MerchantId, active_payout_ids: &[common_utils::id_type::PayoutId], connector: Option<Vec<PayoutConnectors>>, currency: Option<Vec<storage_enums::Currency>>, status: Option<Vec<storage_enums::PayoutStatus>>, payout_type: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, StorageError> { let conn = self .db_store .get_replica_pool() .get() .await .change_context(StorageError::DatabaseConnectionError)?; let connector_strings = connector.as_ref().map(|connectors| { connectors .iter() .map(|c| c.to_string()) .collect::<Vec<String>>() }); DieselPayouts::get_total_count_of_payouts( &conn, merchant_id, active_payout_ids, connector_strings, currency, status, payout_type, ) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 40, "total_crates": null }
fn_clm_storage_impl_update_payout_attempt_8636921705122219769
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payout_attempt // Implementation of crate::RouterStore<T> for PayoutAttemptInterface async fn update_payout_attempt( &self, this: &PayoutAttempt, payout: PayoutAttemptUpdate, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; this.clone() .to_storage_model() .update_with_attempt_id(&conn, payout.to_storage_model()) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 85, "total_crates": null }
fn_clm_storage_impl_to_storage_model_8636921705122219769
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payout_attempt // Implementation of PayoutAttemptUpdate for DataModelExt fn to_storage_model(self) -> Self::StorageModel { match self { Self::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, } => DieselPayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, }, Self::PayoutTokenUpdate { payout_token } => { DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token } } Self::BusinessUpdate { business_country, business_label, address_id, customer_id, } => DieselPayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, }, Self::UpdateRouting { connector, routing_info, merchant_connector_id, } => DieselPayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, }, Self::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => DieselPayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, }, } }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 59, "total_crates": null }
fn_clm_storage_impl_get_filters_for_payouts_8636921705122219769
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payout_attempt // Implementation of crate::RouterStore<T> for PayoutAttemptInterface async fn get_filters_for_payouts( &self, payouts: &[Payouts], merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PayoutListFilters, errors::StorageError> { let conn = pg_connection_read(self).await?; let payouts = payouts .iter() .cloned() .map(|payouts| payouts.to_storage_model()) .collect::<Vec<diesel_models::Payouts>>(); DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map( |(connector, currency, status, payout_method)| PayoutListFilters { connector: connector .iter() .filter_map(|c| { PayoutConnectors::from_str(c) .map_err(|e| { logger::error!( "Failed to parse payout connector '{}' - {}", c, e ); }) .ok() }) .collect(), currency, status, payout_method, }, ) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 53, "total_crates": null }
fn_clm_storage_impl_find_payout_attempt_by_merchant_id_payout_attempt_id_8636921705122219769
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payout_attempt // Implementation of crate::RouterStore<T> for PayoutAttemptInterface async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payout_attempt_id: &str, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; DieselPayoutAttempt::find_by_merchant_id_payout_attempt_id( &conn, merchant_id, payout_attempt_id, ) .await .map(PayoutAttempt::from_storage_model) .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 40, "total_crates": null }
fn_clm_storage_impl_insert_payout_attempt_8636921705122219769
clm
function
// Repository: hyperswitch // Crate: storage_impl // Purpose: Storage backend implementations for database operations // Module: crates/storage_impl/src/payouts/payout_attempt // Implementation of crate::RouterStore<T> for PayoutAttemptInterface async fn insert_payout_attempt( &self, new: PayoutAttemptNew, _payouts: &Payouts, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PayoutAttempt, errors::StorageError> { let conn = pg_connection_write(self).await?; new.to_storage_model() .insert(&conn) .await .map_err(|er| { let new_err = diesel_error_to_data_error(*er.current_context()); er.change_context(new_err) }) .map(PayoutAttempt::from_storage_model) }
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 33, "total_crates": null }
fn_clm_common_utils_valid_range_63747174501507261
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/tests/percentage fn valid_range() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("2.22".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.22) } let percentage = Percentage::<PRECISION_2>::from_string("0.05".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 0.05) } let percentage = Percentage::<PRECISION_2>::from_string("100.0".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 100.0) } Ok(()) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 12, "total_crates": null }
fn_clm_common_utils_valid_precision_63747174501507261
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/tests/percentage fn valid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("2.2".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.2) } let percentage = Percentage::<PRECISION_2>::from_string("2.20000".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.2) } let percentage = Percentage::<PRECISION_0>::from_string("2.0".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.0) } Ok(()) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 12, "total_crates": null }
fn_clm_common_utils_invalid_range_more_than_100_63747174501507261
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/tests/percentage fn invalid_range_more_than_100() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("100.01".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( *err.current_context(), PercentageError::InvalidPercentageValue ) } Ok(()) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 4, "total_crates": null }
fn_clm_common_utils_invalid_range_less_than_0_63747174501507261
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/tests/percentage fn invalid_range_less_than_0() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("-0.01".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( *err.current_context(), PercentageError::InvalidPercentageValue ) } Ok(()) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 4, "total_crates": null }
fn_clm_common_utils_invalid_string_63747174501507261
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/tests/percentage fn invalid_string() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let percentage = Percentage::<PRECISION_2>::from_string("-0.01ed".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( *err.current_context(), PercentageError::InvalidPercentageValue ) } Ok(()) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 4, "total_crates": null }
fn_clm_common_utils_generate_token_4038491806422316239
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/tokenization /// Generates a new token string /// /// # Returns /// A randomly generated token string of length `TOKEN_LENGTH` pub fn generate_token() -> String { use nanoid::nanoid; nanoid!(TOKEN_LENGTH) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 10, "total_crates": null }
fn_clm_common_utils_parse_struct_1952570677639635802
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/ext_traits // Implementation of String for StringExt<T> fn parse_struct<'de>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_str::<T>(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { format!( "Unable to parse {type_name} from string {:?}", Secret::<_, masking::JsonMaskStrategy>::new(serde_json::Value::String( self.clone() )) ) }) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 1442, "total_crates": null }
fn_clm_common_utils_get_required_value_1952570677639635802
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/ext_traits // Implementation of Option<T> for OptionExt<T> fn get_required_value( self, field_name: &'static str, ) -> CustomResult<T, errors::ValidationError> { match self { Some(v) => Ok(v), None => Err(errors::ValidationError::MissingRequiredField { field_name: field_name.to_string(), }) .attach_printable(format!("Missing required field {field_name} in {self:?}")), } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 936, "total_crates": null }
fn_clm_common_utils_parse_value_1952570677639635802
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/ext_traits // Implementation of Option<T> for OptionExt<T> fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned, { let value = self .get_required_value(type_name) .change_context(errors::ParsingError::UnknownError)?; value.parse_value(type_name) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 479, "total_crates": null }
fn_clm_common_utils_async_map_1952570677639635802
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/ext_traits // Implementation of Option<A> for AsyncExt<A> async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send, { match self { Some(a) => Some(func(a).await), None => None, } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 292, "total_crates": null }
fn_clm_common_utils_encode_to_value_1952570677639635802
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/ext_traits // Implementation of A for Encode<'e> fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize, { serde_json::to_value(self) .change_context(errors::ParsingError::EncodeError("json-value")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 202, "total_crates": null }
fn_clm_common_utils_new_6003224971021474921
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/request // Inherent implementation for 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, } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14467, "total_crates": null }
fn_clm_common_utils_default_6003224971021474921
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/request // Implementation of RequestBuilder for Default fn default() -> Self { Self::new() }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 7705, "total_crates": null }
fn_clm_common_utils_headers_6003224971021474921
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/request // Inherent implementation for RequestBuilder pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self { self.headers.extend(headers); self }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 1085, "total_crates": null }
fn_clm_common_utils_build_6003224971021474921
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/request // Inherent implementation for RequestBuilder 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, } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 582, "total_crates": null }
fn_clm_common_utils_method_6003224971021474921
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/request // Inherent implementation for RequestBuilder pub fn method(mut self, method: Method) -> Self { self.method = method; self }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 453, "total_crates": null }
fn_clm_common_utils_default_payments_list_limit_-4950260110414978540
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/consts /// Default limit for payments list API pub fn default_payments_list_limit() -> u32 { 10 }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 10, "total_crates": null }
fn_clm_common_utils_default_payouts_list_limit_-4950260110414978540
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/consts /// Default limit for payouts list API pub fn default_payouts_list_limit() -> u32 { 10 }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 10, "total_crates": null }
fn_clm_common_utils_new_915834656205888258
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/types // Inherent implementation for StringMajorUnit /// forms a new major unit from amount fn new(value: String) -> Self { Self(value) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14455, "total_crates": null }
fn_clm_common_utils_try_from_915834656205888258
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/types // Implementation of UnifiedMessage for TryFrom<String> 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)) } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2661, "total_crates": null }
fn_clm_common_utils_from_915834656205888258
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/types // Implementation of ConnectorTransactionId for From<String> 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) } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2622, "total_crates": null }
fn_clm_common_utils_get_id_915834656205888258
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/types // Implementation of None for ConnectorTransactionId /// Implementation for retrieving the inner identifier pub fn get_id(&self) -> &String { match self { Self::TxnId(id) | Self::HashedData(id) => id, } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2472, "total_crates": null }
fn_clm_common_utils_into_inner_915834656205888258
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/types // Inherent implementation for Url /// Get the inner url pub fn into_inner(self) -> url::Url { self.0 }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2061, "total_crates": null }
fn_clm_common_utils_get_api_event_type_577027735017984470
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/events // Implementation of None for ApiEventMetric fn get_api_event_type(&self) -> Option<ApiEventsType> { T::get_api_event_type(self) }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 28, "total_crates": null }
fn_clm_common_utils_new_-7491340477675652801
clm
function
// Repository: hyperswitch // Crate: common_utils // Purpose: Utility functions shared across crates // Module: crates/common_utils/src/encryption // Inherent implementation for Encryption pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self { Self { inner: item } }
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14463, "total_crates": null }