Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix: added find all support for pm kv (#4357)
akshay-975b811aac0049
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex c885a3bf22..8776730899 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -2832,6 +2832,7 @@ pub async fn list_customer_payment_method(&merchant_account.merchant_id,common_enums::PaymentMethodStatus::Active,limit,+ merchant_account.storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex a831f5cbd7..7da40e505e 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -1440,6 +1440,7 @@ impl PaymentMethodInterface for KafkaStore {merchant_id: &str,status: common_enums::PaymentMethodStatus,limit: Option<i64>,+ storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {self.diesel_store.find_payment_method_by_customer_id_merchant_id_status(@@ -1447,6 +1448,7 @@ impl PaymentMethodInterface for KafkaStore {merchant_id,status,limit,+ storage_scheme,).await}diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rsindex 50a70ec58a..72676ca81e 100644--- a/crates/router/src/db/payment_method.rs+++ b/crates/router/src/db/payment_method.rs@@ -34,6 +34,7 @@ pub trait PaymentMethodInterface {merchant_id: &str,status: common_enums::PaymentMethodStatus,limit: Option<i64>,+ storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError>;async fn get_payment_method_count_by_customer_id_merchant_id_status(@@ -63,329 +64,368 @@ pub trait PaymentMethodInterface {) -> CustomResult<storage_types::PaymentMethod, errors::StorageError>;}-// #[cfg(feature = "kv_store")]-// mod storage {-// use common_utils::fallback_reverse_lookup_not_found;-// use diesel_models::{kv, PaymentMethodUpdateInternal};-// use error_stack::{report, ResultExt};-// use redis_interface::HsetnxReply;-// use router_env::{instrument, tracing};-// use storage_impl::redis::kv_store::{kv_wrapper, KvOperation, PartitionKey};--// use super::PaymentMethodInterface;-// use crate::{-// connection,-// core::errors::{self, utils::RedisErrorExt, CustomResult},-// db::reverse_lookup::ReverseLookupInterface,-// services::Store,-// types::storage::{self as storage_types, enums::MerchantStorageScheme},-// utils::db_utils,-// };--// #[async_trait::async_trait]-// impl PaymentMethodInterface for Store {-// #[instrument(skip_all)]-// async fn find_payment_method(-// &self,-// payment_method_id: &str,-// storage_scheme: MerchantStorageScheme,-// ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {-// let conn = connection::pg_connection_read(self).await?;-// let database_call = || async {-// storage_types::PaymentMethod::find_by_payment_method_id(&conn, payment_method_id)-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// };--// match storage_scheme {-// MerchantStorageScheme::PostgresOnly => database_call().await,-// MerchantStorageScheme::RedisKv => {-// let lookup_id = format!("payment_method_{}", payment_method_id);-// let lookup = fallback_reverse_lookup_not_found!(-// self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)-// .await,-// database_call().await-// );--// let key = PartitionKey::CombinationKey {-// combination: &lookup.pk_id,-// };--// Box::pin(db_utils::try_redis_get_else_try_database_get(-// async {-// kv_wrapper(-// self,-// KvOperation::<storage_types::PaymentMethod>::HGet(&lookup.sk_id),-// key,-// )-// .await?-// .try_into_hget()-// },-// database_call,-// ))-// .await-// }-// }-// }--// #[instrument(skip_all)]-// async fn find_payment_method_by_locker_id(-// &self,-// locker_id: &str,-// storage_scheme: MerchantStorageScheme,-// ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {-// let conn = connection::pg_connection_read(self).await?;-// let database_call = || async {-// storage_types::PaymentMethod::find_by_locker_id(&conn, locker_id)-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// };--// match storage_scheme {-// MerchantStorageScheme::PostgresOnly => database_call().await,-// MerchantStorageScheme::RedisKv => {-// let lookup_id = format!("payment_method_locker_{}", locker_id);-// let lookup = fallback_reverse_lookup_not_found!(-// self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)-// .await,-// database_call().await-// );--// let key = PartitionKey::CombinationKey {-// combination: &lookup.pk_id,-// };--// Box::pin(db_utils::try_redis_get_else_try_database_get(-// async {-// kv_wrapper(-// self,-// KvOperation::<storage_types::PaymentMethod>::HGet(&lookup.sk_id),-// key,-// )-// .await?-// .try_into_hget()-// },-// database_call,-// ))-// .await-// }-// }-// }-// // not supported in kv-// #[instrument(skip_all)]-// async fn get_payment_method_count_by_customer_id_merchant_id_status(-// &self,-// customer_id: &str,-// merchant_id: &str,-// status: common_enums::PaymentMethodStatus,-// ) -> CustomResult<i64, errors::StorageError> {-// let conn = connection::pg_connection_read(self).await?;-// storage_types::PaymentMethod::get_count_by_customer_id_merchant_id_status(-// &conn,-// customer_id,-// merchant_id,-// status,-// )-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// }--// #[instrument(skip_all)]-// async fn insert_payment_method(-// &self,-// payment_method_new: storage_types::PaymentMethodNew,-// storage_scheme: MerchantStorageScheme,-// ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {-// match storage_scheme {-// MerchantStorageScheme::PostgresOnly => {-// let conn = connection::pg_connection_write(self).await?;-// payment_method_new-// .insert(&conn)-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// }-// MerchantStorageScheme::RedisKv => {-// let merchant_id = payment_method_new.merchant_id.clone();-// let customer_id = payment_method_new.customer_id.clone();--// let key = PartitionKey::MerchantIdCustomerId {-// merchant_id: &merchant_id,-// customer_id: &customer_id,-// };-// let key_str = key.to_string();-// let field =-// format!("payment_method_id_{}", payment_method_new.payment_method_id);--// let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew {-// sk_id: field.clone(),-// pk_id: key_str.clone(),-// lookup_id: v,-// source: "payment_method".to_string(),-// updated_by: storage_scheme.to_string(),-// };--// let lookup_id1 =-// format!("payment_method_{}", &payment_method_new.payment_method_id);-// let mut reverse_lookups = vec![lookup_id1];-// if let Some(locker_id) = &payment_method_new.locker_id {-// reverse_lookups.push(format!("payment_method_locker_{}", locker_id))-// }--// let results = reverse_lookups.into_iter().map(|v| {-// self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme)-// });--// futures::future::try_join_all(results).await?;--// let storage_payment_method = (&payment_method_new).into();--// let redis_entry = kv::TypedSql {-// op: kv::DBOperation::Insert {-// insertable: kv::Insertable::PaymentMethod(payment_method_new),-// },-// };--// match kv_wrapper::<diesel_models::PaymentMethod, _, _>(-// self,-// KvOperation::<diesel_models::PaymentMethod>::HSetNx(-// &field,-// &storage_payment_method,-// 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_method",-// key: Some(storage_payment_method.payment_method_id),-// }-// .into()),-// Ok(HsetnxReply::KeySet) => Ok(storage_payment_method),-// Err(er) => Err(er).change_context(errors::StorageError::KVError),-// }-// }-// }-// }--// #[instrument(skip_all)]-// async fn update_payment_method(-// &self,-// payment_method: storage_types::PaymentMethod,-// payment_method_update: storage_types::PaymentMethodUpdate,-// storage_scheme: MerchantStorageScheme,-// ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {-// match storage_scheme {-// MerchantStorageScheme::PostgresOnly => {-// let conn = connection::pg_connection_write(self).await?;-// payment_method-// .update_with_payment_method_id(&conn, payment_method_update.into())-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// }-// MerchantStorageScheme::RedisKv => {-// let merchant_id = payment_method.merchant_id.clone();-// let customer_id = payment_method.customer_id.clone();-// let key = PartitionKey::MerchantIdCustomerId {-// merchant_id: &merchant_id,-// customer_id: &customer_id,-// };-// let key_str = key.to_string();-// let field = format!("payment_method_id_{}", payment_method.payment_method_id);--// let p_update: PaymentMethodUpdateInternal = payment_method_update.into();-// let updated_payment_method =-// p_update.clone().apply_changeset(payment_method.clone());--// let redis_value = serde_json::to_string(&updated_payment_method)-// .change_context(errors::StorageError::SerializationFailed)?;--// let redis_entry = kv::TypedSql {-// op: kv::DBOperation::Update {-// updatable: kv::Updateable::PaymentMethodUpdate(-// kv::PaymentMethodUpdateMems {-// orig: payment_method,-// update_data: p_update,-// },-// ),-// },-// };--// kv_wrapper::<(), _, _>(-// self,-// KvOperation::<diesel_models::PaymentMethod>::Hset(-// (&field, redis_value),-// redis_entry,-// ),-// key,-// )-// .await-// .map_err(|err| err.to_redis_failed_response(&key_str))?-// .try_into_hset()-// .change_context(errors::StorageError::KVError)?;--// Ok(updated_payment_method)-// }-// }-// }--// #[instrument(skip_all)]-// async fn find_payment_method_by_customer_id_merchant_id_list(-// &self,-// customer_id: &str,-// merchant_id: &str,-// limit: Option<i64>,-// ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {-// let conn = connection::pg_connection_read(self).await?;-// storage_types::PaymentMethod::find_by_customer_id_merchant_id(-// &conn,-// customer_id,-// merchant_id,-// limit,-// )-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// }--// #[instrument(skip_all)]-// async fn find_payment_method_by_customer_id_merchant_id_status(-// &self,-// customer_id: &str,-// merchant_id: &str,-// status: common_enums::PaymentMethodStatus,-// limit: Option<i64>,-// ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {-// let conn = connection::pg_connection_read(self).await?;-// storage_types::PaymentMethod::find_by_customer_id_merchant_id_status(-// &conn,-// customer_id,-// merchant_id,-// status,-// limit,-// )-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// }--// async fn delete_payment_method_by_merchant_id_payment_method_id(-// &self,-// merchant_id: &str,-// payment_method_id: &str,-// ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {-// let conn = connection::pg_connection_write(self).await?;-// storage_types::PaymentMethod::delete_by_merchant_id_payment_method_id(-// &conn,-// merchant_id,-// payment_method_id,-// )-// .await-// .map_err(|error| report!(errors::StorageError::from(error)))-// }-// }-// }+#[cfg(feature = "kv_store")]+mod storage {+ use common_utils::fallback_reverse_lookup_not_found;+ use diesel_models::{kv, PaymentMethodUpdateInternal};+ use error_stack::{report, ResultExt};+ use redis_interface::HsetnxReply;+ use router_env::{instrument, tracing};+ use storage_impl::redis::kv_store::{kv_wrapper, KvOperation, PartitionKey};++ use super::PaymentMethodInterface;+ use crate::{+ connection,+ core::errors::{self, utils::RedisErrorExt, CustomResult},+ db::reverse_lookup::ReverseLookupInterface,+ services::Store,+ types::storage::{self as storage_types, enums::MerchantStorageScheme},+ utils::db_utils,+ };++ #[async_trait::async_trait]+ impl PaymentMethodInterface for Store {+ #[instrument(skip_all)]+ async fn find_payment_method(+ &self,+ payment_method_id: &str,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ let database_call = || async {+ storage_types::PaymentMethod::find_by_payment_method_id(&conn, payment_method_id)+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ };++ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => database_call().await,+ MerchantStorageScheme::RedisKv => {+ let lookup_id = format!("payment_method_{}", payment_method_id);+ let lookup = fallback_reverse_lookup_not_found!(+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)+ .await,+ database_call().await+ );++ let key = PartitionKey::CombinationKey {+ combination: &lookup.pk_id,+ };++ Box::pin(db_utils::try_redis_get_else_try_database_get(+ async {+ kv_wrapper(+ self,+ KvOperation::<storage_types::PaymentMethod>::HGet(&lookup.sk_id),+ key,+ )+ .await?+ .try_into_hget()+ },+ database_call,+ ))+ .await+ }+ }+ }++ #[instrument(skip_all)]+ async fn find_payment_method_by_locker_id(+ &self,+ locker_id: &str,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ let database_call = || async {+ storage_types::PaymentMethod::find_by_locker_id(&conn, locker_id)+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ };++ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => database_call().await,+ MerchantStorageScheme::RedisKv => {+ let lookup_id = format!("payment_method_locker_{}", locker_id);+ let lookup = fallback_reverse_lookup_not_found!(+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)+ .await,+ database_call().await+ );++ let key = PartitionKey::CombinationKey {+ combination: &lookup.pk_id,+ };++ Box::pin(db_utils::try_redis_get_else_try_database_get(+ async {+ kv_wrapper(+ self,+ KvOperation::<storage_types::PaymentMethod>::HGet(&lookup.sk_id),+ key,+ )+ .await?+ .try_into_hget()+ },+ database_call,+ ))+ .await+ }+ }+ }+ // not supported in kv+ #[instrument(skip_all)]+ async fn get_payment_method_count_by_customer_id_merchant_id_status(+ &self,+ customer_id: &str,+ merchant_id: &str,+ status: common_enums::PaymentMethodStatus,+ ) -> CustomResult<i64, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage_types::PaymentMethod::get_count_by_customer_id_merchant_id_status(+ &conn,+ customer_id,+ merchant_id,+ status,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }++ #[instrument(skip_all)]+ async fn insert_payment_method(+ &self,+ payment_method_new: storage_types::PaymentMethodNew,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {+ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => {+ let conn = connection::pg_connection_write(self).await?;+ payment_method_new+ .insert(&conn)+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+ MerchantStorageScheme::RedisKv => {+ let merchant_id = payment_method_new.merchant_id.clone();+ let customer_id = payment_method_new.customer_id.clone();++ let key = PartitionKey::MerchantIdCustomerId {+ merchant_id: &merchant_id,+ customer_id: &customer_id,+ };+ let key_str = key.to_string();+ let field =+ format!("payment_method_id_{}", payment_method_new.payment_method_id);++ let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew {+ sk_id: field.clone(),+ pk_id: key_str.clone(),+ lookup_id: v,+ source: "payment_method".to_string(),+ updated_by: storage_scheme.to_string(),+ };++ let lookup_id1 =+ format!("payment_method_{}", &payment_method_new.payment_method_id);+ let mut reverse_lookups = vec![lookup_id1];+ if let Some(locker_id) = &payment_method_new.locker_id {+ reverse_lookups.push(format!("payment_method_locker_{}", locker_id))+ }++ let results = reverse_lookups.into_iter().map(|v| {+ self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme)+ });++ futures::future::try_join_all(results).await?;++ let storage_payment_method = (&payment_method_new).into();++ let redis_entry = kv::TypedSql {+ op: kv::DBOperation::Insert {+ insertable: kv::Insertable::PaymentMethod(payment_method_new),+ },+ };++ match kv_wrapper::<diesel_models::PaymentMethod, _, _>(+ self,+ KvOperation::<diesel_models::PaymentMethod>::HSetNx(+ &field,+ &storage_payment_method,+ 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_method",+ key: Some(storage_payment_method.payment_method_id),+ }+ .into()),+ Ok(HsetnxReply::KeySet) => Ok(storage_payment_method),+ Err(er) => Err(er).change_context(errors::StorageError::KVError),+ }+ }+ }+ }+ #[instrument(skip_all)]+ async fn update_payment_method(+ &self,+ payment_method: storage_types::PaymentMethod,+ payment_method_update: storage_types::PaymentMethodUpdate,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {+ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => {+ let conn = connection::pg_connection_write(self).await?;+ payment_method+ .update_with_payment_method_id(&conn, payment_method_update.into())+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+ MerchantStorageScheme::RedisKv => {+ let merchant_id = payment_method.merchant_id.clone();+ let customer_id = payment_method.customer_id.clone();+ let key = PartitionKey::MerchantIdCustomerId {+ merchant_id: &merchant_id,+ customer_id: &customer_id,+ };+ let key_str = key.to_string();+ let field = format!("payment_method_id_{}", payment_method.payment_method_id);++ let p_update: PaymentMethodUpdateInternal = payment_method_update.into();+ let updated_payment_method =+ p_update.clone().apply_changeset(payment_method.clone());++ let redis_value = serde_json::to_string(&updated_payment_method)+ .change_context(errors::StorageError::SerializationFailed)?;++ let redis_entry = kv::TypedSql {+ op: kv::DBOperation::Update {+ updatable: kv::Updateable::PaymentMethodUpdate(+ kv::PaymentMethodUpdateMems {+ orig: payment_method,+ update_data: p_update,+ },+ ),+ },+ };++ kv_wrapper::<(), _, _>(+ self,+ KvOperation::<diesel_models::PaymentMethod>::Hset(+ (&field, redis_value),+ redis_entry,+ ),+ key,+ )+ .await+ .map_err(|err| err.to_redis_failed_response(&key_str))?+ .try_into_hset()+ .change_context(errors::StorageError::KVError)?;++ Ok(updated_payment_method)+ }+ }+ }++ #[instrument(skip_all)]+ async fn find_payment_method_by_customer_id_merchant_id_list(+ &self,+ customer_id: &str,+ merchant_id: &str,+ limit: Option<i64>,+ ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage_types::PaymentMethod::find_by_customer_id_merchant_id(+ &conn,+ customer_id,+ merchant_id,+ limit,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }++ #[instrument(skip_all)]+ async fn find_payment_method_by_customer_id_merchant_id_status(+ &self,+ customer_id: &str,+ merchant_id: &str,+ status: common_enums::PaymentMethodStatus,+ limit: Option<i64>,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ let database_call = || async {+ storage_types::PaymentMethod::find_by_customer_id_merchant_id_status(+ &conn,+ customer_id,+ merchant_id,+ status,+ limit,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ };++ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => database_call().await,+ MerchantStorageScheme::RedisKv => {+ let key = PartitionKey::MerchantIdCustomerId {+ merchant_id,+ customer_id,+ };++ let pattern = "payment_method_id_*";++ let redis_fut = async {+ let kv_result = kv_wrapper::<storage_types::PaymentMethod, _, _>(+ self,+ KvOperation::<storage_types::PaymentMethod>::Scan(pattern),+ key,+ )+ .await?+ .try_into_scan();+ kv_result.map(|payment_methods| {+ payment_methods+ .into_iter()+ .filter(|pm| pm.status == status)+ .collect()+ })+ };++ Box::pin(db_utils::find_all_combined_kv_database(+ redis_fut,+ database_call,+ limit,+ ))+ .await+ }+ }+ }++ async fn delete_payment_method_by_merchant_id_payment_method_id(+ &self,+ merchant_id: &str,+ payment_method_id: &str,+ ) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ storage_types::PaymentMethod::delete_by_merchant_id_payment_method_id(+ &conn,+ merchant_id,+ payment_method_id,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+ }+}++#[cfg(not(feature = "kv_store"))]mod storage {use error_stack::report;use router_env::{instrument, tracing};@@ -493,6 +533,7 @@ mod storage {merchant_id: &str,status: common_enums::PaymentMethodStatus,limit: Option<i64>,+ _storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage_types::PaymentMethod::find_by_customer_id_merchant_id_status(@@ -654,6 +695,7 @@ impl PaymentMethodInterface for MockDb {merchant_id: &str,status: common_enums::PaymentMethodStatus,_limit: Option<i64>,+ _storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {let payment_methods = self.payment_methods.lock().await;let payment_methods_found: Vec<storage_types::PaymentMethod> = payment_methodsdiff --git a/crates/router/src/utils/db_utils.rs b/crates/router/src/utils/db_utils.rsindex 219b6f9777..67641a3fe7 100644--- a/crates/router/src/utils/db_utils.rs+++ b/crates/router/src/utils/db_utils.rs@@ -36,3 +36,73 @@ where},}}++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>, errors::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>, errors::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()+ .map_or(true, |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(&metrics::CONTEXT, 1, &[]);+ database_call().await+ }+ // Keeping the key empty here since the error would never go here.+ _ => Err(redis_error.to_redis_failed_response("")),+ },+ }+}++use std::collections::HashSet;++use storage_impl::UniqueConstraints;++fn union_vec<T>(mut kv_rows: Vec<T>, sql_rows: Vec<T>) -> Vec<T>+where+ T: UniqueConstraints,+{+ let mut kv_unique_keys = HashSet::new();++ kv_rows.iter().for_each(|v| {+ kv_unique_keys.insert(v.unique_constraints().concat());+ });++ sql_rows.into_iter().for_each(|v| {+ let unique_key = v.unique_constraints().concat();+ if !kv_unique_keys.contains(&unique_key) {+ kv_rows.push(v);+ }+ });++ kv_rows+}