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
perf(core): Fetch MCA list by profile_id (#13334)
Anurag Thakur8dd1b6b9a85c
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rsindex be3a2351c2..2305a1ea56 100644--- a/crates/diesel_models/src/query/merchant_connector_account.rs+++ b/crates/diesel_models/src/query/merchant_connector_account.rs@@ -170,6 +170,51 @@ impl MerchantConnectorAccount {).await}++ pub async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ conn: &PgPooledConn,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<+ <Self as HasTable>::Table,+ _,+ <<Self as HasTable>::Table as Table>::PrimaryKey,+ _,+ >(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::profile_id.eq(profile_id.to_owned())),+ None,+ None,+ None,+ )+ .await+ }++ pub async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ conn: &PgPooledConn,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<+ <Self as HasTable>::Table,+ _,+ <<Self as HasTable>::Table as Table>::PrimaryKey,+ _,+ >(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::profile_id.eq(profile_id.to_owned()))+ .and(dsl::disabled.eq(false)),+ None,+ None,+ None,+ )+ .await+ }}#[cfg(feature = "v2")]@@ -260,6 +305,51 @@ impl MerchantConnectorAccount {.await}+ pub async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ conn: &PgPooledConn,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<+ <Self as HasTable>::Table,+ _,+ <<Self as HasTable>::Table as Table>::PrimaryKey,+ _,+ >(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::profile_id.eq(profile_id.to_owned())),+ None,+ None,+ None,+ )+ .await+ }++ pub async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ conn: &PgPooledConn,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<+ <Self as HasTable>::Table,+ _,+ <<Self as HasTable>::Table as Table>::PrimaryKey,+ _,+ >(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::profile_id.eq(profile_id.to_owned()))+ .and(dsl::disabled.eq(false)),+ None,+ None,+ None,+ )+ .await+ }+pub async fn list_enabled_by_profile_id(conn: &PgPooledConn,profile_id: &common_utils::id_type::ProfileId,diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rsindex 286ea1fe6f..8000f2ef95 100644--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs@@ -938,31 +938,7 @@ common_utils::create_list_wrapper!(MerchantConnectorAccounts,MerchantConnectorAccount,impl_functions: {- fn filter_and_map<'a, T>(- &'a self,- filter: impl Fn(&'a MerchantConnectorAccount) -> bool,- func: impl Fn(&'a MerchantConnectorAccount) -> T,- ) -> rustc_hash::FxHashSet<T>- where- T: std::hash::Hash + Eq,- {- self.0- .iter()- .filter(|mca| filter(mca))- .map(func)- .collect::<rustc_hash::FxHashSet<_>>()- }- pub fn filter_by_profile<'a, T>(- &'a self,- profile_id: &'a id_type::ProfileId,- func: impl Fn(&'a MerchantConnectorAccount) -> T,- ) -> rustc_hash::FxHashSet<T>- where- T: std::hash::Hash + Eq,- {- self.filter_and_map(|mca| mca.profile_id == *profile_id, func)- }#[cfg(feature = "v2")]pub fn get_connector_and_supporting_payment_method_type_for_session_call(&self,@@ -986,26 +962,13 @@ common_utils::create_list_wrapper!(}).collect();connector_and_supporting_payment_method_type}- pub fn filter_based_on_profile_and_connector_type(- self,- profile_id: &id_type::ProfileId,- connector_type: common_enums::ConnectorType,- ) -> Self {- self.into_iter()- .filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type)- .collect()- }+pub fn is_merchant_connector_account_id_in_connector_mandate_details(&self,- profile_id: Option<&id_type::ProfileId>,connector_mandate_details: &CommonMandateReference,) -> bool {let mca_ids = self.iter()- .filter(|mca| {- mca.disabled.is_some_and(|disabled| !disabled)- && profile_id.is_some_and(|profile_id| *profile_id == mca.profile_id)- }).map(|mca| mca.get_id()).collect::<std::collections::HashSet<_>>();@@ -1181,31 +1144,7 @@ common_utils::create_list_wrapper!(MerchantConnectorAccountsWithoutEncrypted,MerchantConnectorAccountWithoutEncrypted,impl_functions: {- fn filter_and_map<'a, T>(- &'a self,- filter: impl Fn(&'a MerchantConnectorAccountWithoutEncrypted) -> bool,- func: impl Fn(&'a MerchantConnectorAccountWithoutEncrypted) -> T,- ) -> rustc_hash::FxHashSet<T>- where- T: std::hash::Hash + Eq,- {- self.0- .iter()- .filter(|mca| filter(mca))- .map(func)- .collect::<rustc_hash::FxHashSet<_>>()- }- pub fn filter_by_profile<'a, T>(- &'a self,- profile_id: &'a id_type::ProfileId,- func: impl Fn(&'a MerchantConnectorAccountWithoutEncrypted) -> T,- ) -> rustc_hash::FxHashSet<T>- where- T: std::hash::Hash + Eq,- {- self.filter_and_map(|mca| mca.profile_id == *profile_id, func)- }#[cfg(feature = "v2")]pub fn get_connector_and_supporting_payment_method_type_for_session_call(&self,@@ -1229,26 +1168,21 @@ common_utils::create_list_wrapper!(}).collect();connector_and_supporting_payment_method_type}- pub fn filter_based_on_profile_and_connector_type(++ pub fn filter_by_connector_type(self,- profile_id: &id_type::ProfileId,connector_type: common_enums::ConnectorType,) -> Self {self.into_iter()- .filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type)+ .filter(|mca| mca.connector_type == connector_type).collect()}pub fn is_merchant_connector_account_id_in_connector_mandate_details(&self,- profile_id: Option<&id_type::ProfileId>,connector_mandate_details: &CommonMandateReference,) -> bool {let mca_ids = self.iter()- .filter(|mca| {- mca.disabled.is_some_and(|disabled| !disabled)- && profile_id.is_some_and(|profile_id| *profile_id == mca.profile_id)- }).map(|mca| mca.get_id()).collect::<std::collections::HashSet<_>>();@@ -1377,6 +1311,24 @@ whereget_disabled: bool,) -> CustomResult<MerchantConnectorAccountsWithoutEncrypted, Self::Error>;+ /// Like [`Self::find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list`],+ /// but additionally filters by `profile_id` at the database level, avoiding+ /// the need to fetch all MCAs for the merchant and then filter in memory.+ /// Returns all MCAs including disabled ones.+ async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ &self,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ ) -> CustomResult<MerchantConnectorAccountsWithoutEncrypted, Self::Error>;++ /// Like [`Self::list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id`], but+ /// only returns enabled (non-disabled) MCAs.+ async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ &self,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ ) -> CustomResult<MerchantConnectorAccountsWithoutEncrypted, Self::Error>;+#[cfg(all(feature = "olap", feature = "v2"))]async fn list_connector_account_by_profile_id(&self,diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex b5bbf19cd6..5966ec3d7c 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -1574,31 +1574,25 @@ impl PMAuthConfigValidation<'_> {}).attach_printable("Failed to deserialize Payment Method Auth config")?;+ // Fetching disabled MCAs too: PM auth config may reference MCAs that are+ // temporarily disabled — validation checks existence, not activity.let all_mcas = self.db- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(self.merchant_id,- true,+ self.profile_id,).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: self.merchant_id.get_string_repr().to_owned(),})?;for conn_choice in config.enabled_payment_methods {- let pm_auth_mca = all_mcas+ all_mcas.iter().find(|mca| mca.get_id() == conn_choice.mca_id).ok_or(errors::ApiErrorResponse::GenericNotFoundError {message: "payment method auth connector account not found".to_string(),})?;-- if &pm_auth_mca.profile_id != self.profile_id {- return Err(errors::ApiErrorResponse::GenericNotFoundError {- message: "payment method auth profile_id differs from connector profile_id"- .to_string(),- }- .into());- }}Ok(services::ApplicationResponse::StatusOk)@@ -2896,12 +2890,11 @@ async fn validate_pm_auth(}).attach_printable("Failed to deserialize Payment Method Auth config")?;+ // Fetching disabled MCAs too: PM auth config may reference MCAs that are+ // temporarily disabled — validation checks existence, not activity.let all_mcas = state.store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(- merchant_id,- true,- )+ .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: platform@@ -2913,20 +2906,12 @@ async fn validate_pm_auth(})?;for conn_choice in config.enabled_payment_methods {- let pm_auth_mca = all_mcas+ all_mcas.iter().find(|mca| mca.get_id() == conn_choice.mca_id).ok_or(errors::ApiErrorResponse::GenericNotFoundError {message: "payment method auth connector account not found".to_string(),})?;-- if &pm_auth_mca.profile_id != profile_id {- return Err(errors::ApiErrorResponse::GenericNotFoundError {- message: "payment method auth profile_id differs from connector profile_id"- .to_string(),- }- .into());- }}Ok(services::ApplicationResponse::StatusOk)diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex b6c0caa87b..efe531d90b 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -3994,17 +3994,17 @@ pub async fn build_merchant_enabled_pms_context(let db = &*state.store;let pm_config_mapping = &state.conf.pm_filters;- // --- Load all MCAs and filter by profile + connector type ---+ // --- Load all MCAs and filter by connector type ---+ let profile_id = business_profile.get_id().clone();+let all_mcas = db- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),- false,+ &profile_id,).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let profile_id = business_profile.get_id().clone();-let dimensions = dimension_state::Dimensions::new().with_processor_merchant_id(platform.get_processor().get_processor_merchant_id()).with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())@@ -4012,7 +4012,7 @@ pub async fn build_merchant_enabled_pms_context(let filtered_mcas = all_mcas.clone()- .filter_based_on_profile_and_connector_type(&profile_id, ConnectorType::PaymentProcessor);+ .filter_by_connector_type(ConnectorType::PaymentProcessor);logger::debug!(mca_before_filtering=?filtered_mcas);@@ -5793,21 +5793,29 @@ pub async fn list_customer_payment_method(.and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled).unwrap_or(false);- let merchant_connector_accounts = state- .store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(- platform.get_processor().get_account().get_id(),- true,- )- .await- .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: platform- .get_processor()- .get_account()- .get_id()- .get_string_repr()- .to_owned(),- })?;+ // The MCA list is used to evaluate if the payment method has connector_mandate_details for any active MCA+ let merchant_connector_accounts = match business_profile.as_ref() {+ Some(business_profile) => Some(+ state+ .store+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ platform.get_processor().get_account().get_id(),+ business_profile.get_id(),+ )+ .await+ .change_context(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: platform+ .get_processor()+ .get_account()+ .get_id()+ .get_string_repr()+ .to_owned(),+ },+ )?,+ ),+ None => None,+ };for pm in resp.into_iter() {let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");@@ -5857,11 +5865,10 @@ pub async fn list_customer_payment_method(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to deserialize to Payment Mandate Reference ")?;let mca_enabled = get_mca_status(- profile_id.clone(),is_connector_agnostic_mit_enabled,Some(connector_mandate_details),pm.network_transaction_id.as_ref(),- &merchant_connector_accounts,+ merchant_connector_accounts.as_ref(),).await?;@@ -6140,20 +6147,17 @@ pub async fn perform_surcharge_ops(#[cfg(feature = "v1")]pub async fn get_mca_status(- profile_id: Option<id_type::ProfileId>,-is_connector_agnostic_mit_enabled: bool,connector_mandate_details: Option<CommonMandateReference>,network_transaction_id: Option<&String>,- merchant_connector_accounts: &domain::MerchantConnectorAccountsWithoutEncrypted,+ merchant_connector_accounts: Option<&domain::MerchantConnectorAccountsWithoutEncrypted>,) -> errors::RouterResult<bool> {let agnostic_mit = is_connector_agnostic_mit_enabled && network_transaction_id.is_some();let mandate_match = connector_mandate_details.is_some_and(|details| {- merchant_connector_accounts.is_merchant_connector_account_id_in_connector_mandate_details(- profile_id.as_ref(),- &details,- )+ merchant_connector_accounts.is_some_and(|mcas| {+ mcas.is_merchant_connector_account_id_in_connector_mandate_details(&details)+ })});Ok(agnostic_mit || mandate_match)@@ -6164,23 +6168,20 @@ pub async fn get_mca_status(pub async fn get_mca_status(state: &routes::SessionState,key_store: &domain::MerchantKeyStore,- profile_id: Option<id_type::ProfileId>,merchant_id: &id_type::MerchantId,is_connector_agnostic_mit_enabled: bool,connector_mandate_details: Option<&CommonMandateReference>,network_transaction_id: Option<&String>,- merchant_connector_accounts: &domain::MerchantConnectorAccounts,+ merchant_connector_accounts: Option<&domain::MerchantConnectorAccounts>,) -> bool {if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() {return true;}- match connector_mandate_details {- Some(connector_mandate_details) => merchant_connector_accounts- .is_merchant_connector_account_id_in_connector_mandate_details(- profile_id.as_ref(),- connector_mandate_details,- ),- None => false,+ match (connector_mandate_details, merchant_connector_accounts) {+ (Some(details), Some(mcas)) => {+ mcas.is_merchant_connector_account_id_in_connector_mandate_details(details)+ }+ _ => false,}}diff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rsindex e13a7c9c2d..2462c9e017 100644--- a/crates/router/src/core/payment_methods/client.rs+++ b/crates/router/src/core/payment_methods/client.rs@@ -195,28 +195,23 @@ impl CustomerPaymentMethodsFetcher for ModularCustomerPaymentMethodsFetcher {).await;- // Fetch all MCAs for the merchant so we can check whether the connector that- // issued a mandate token is still active for this profile — mirroring the+ // Fetch enabled MCAs for the merchant so we can check whether the connector that+ // issued a mandate token is still enabled for this profile — mirroring the// `get_mca_status` check performed in the legacy DB flow.let merchant_connector_accounts = state.store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(&merchant_id,- true,+ &self.profile_id,).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: merchant_id.get_string_repr().to_owned(),})?;- // Pre-compute the set of MCA IDs that are active for this profilelet active_mca_ids: std::collections::HashSet<id_type::MerchantConnectorAccountId> =merchant_connector_accounts.iter()- .filter(|mca| {- mca.disabled.is_some_and(|disabled| !disabled)- && mca.profile_id == self.profile_id- }).map(|mca| mca.get_id()).collect();diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex f2e38ac6cf..880c41cc88 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -12386,11 +12386,12 @@ where{let chosen = connectors.apply_filter_for_session_routing();- let active_mca_ids = routing::get_active_mca_ids(&state, processor.get_key_store())- .await- .change_context(errors::ApiErrorResponse::GenericNotFoundError {- message: "Active mca_ids not found".to_string(),- })?;+ let active_mca_ids =+ routing::get_active_mca_ids(&state, processor.get_key_store(), business_profile.get_id())+ .await+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {+ message: "Active mca_ids not found".to_string(),+ })?;let session_input = routing::SessionRoutingInput {state: &state,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 5e61e25d09..e5b0eff397 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -6965,18 +6965,15 @@ pub async fn get_apple_pay_retryable_connectors()? {let merchant_connector_account_list = state.store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(processor.get_account().get_id(),- false,+ profile_id,).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;let profile_specific_merchant_connector_account_list = merchant_connector_account_list- .filter_based_on_profile_and_connector_type(- profile_id,- ConnectorType::PaymentProcessor,- );+ .filter_by_connector_type(ConnectorType::PaymentProcessor);let mut connector_data_list = vec![pre_decided_connector_data_first.clone()];@@ -9294,19 +9291,16 @@ pub async fn validate_allowed_payment_method_types_request(if let Some(allowed_payment_method_types) = allowed_payment_method_types {let db = &*state.store;let all_connector_accounts = db- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(processor.get_account().get_id(),- false,+ profile_id,).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to fetch merchant connector account for given merchant id")?;- let filtered_connector_accounts = all_connector_accounts- .filter_based_on_profile_and_connector_type(- profile_id,- ConnectorType::PaymentProcessor,- );+ let filtered_connector_accounts =+ all_connector_accounts.filter_by_connector_type(ConnectorType::PaymentProcessor);let supporting_payment_method_types: HashSet<_> = filtered_connector_accounts.iter()diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rsindex 0a3ea5ccf8..818bd64d1b 100644--- a/crates/router/src/core/payments/operations/payment_session.rs+++ b/crates/router/src/core/payments/operations/payment_session.rs@@ -407,15 +407,6 @@ where) -> RouterResult<api::ConnectorChoice> {let db = &state.store;- let all_connector_accounts = db- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(- processor.get_account().get_id(),- false,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Database error when querying for merchant connector accounts")?;-let profile_id = payment_intent.profile_id.clone()@@ -423,11 +414,17 @@ where.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("profile_id is not set in payment_intent")?;- let filtered_connector_accounts = all_connector_accounts- .filter_based_on_profile_and_connector_type(+ let all_connector_accounts = db+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ processor.get_account().get_id(),&profile_id,- common_enums::ConnectorType::PaymentProcessor,- );+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Database error when querying for merchant connector accounts")?;++ let filtered_connector_accounts = all_connector_accounts+ .filter_by_connector_type(common_enums::ConnectorType::PaymentProcessor);let requested_payment_method_types = request.wallets.clone();let mut connector_and_supporting_payment_method_type = Vec::new();diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rsindex 0cd587cfad..617fa9e0ae 100644--- a/crates/router/src/core/payments/operations/payment_session_intent.rs+++ b/crates/router/src/core/payments/operations/payment_session_intent.rs@@ -275,20 +275,17 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsSessionRequest, payments::Paymentpayment_data: &mut payments::PaymentIntentData<F>,) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {let db = &state.store;+ let profile_id = business_profile.get_id();let all_connector_accounts = db- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),- false,+ profile_id,).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Database error when querying for merchant connector accounts")?;- let profile_id = business_profile.get_id();let filtered_connector_accounts = all_connector_accounts- .filter_based_on_profile_and_connector_type(- profile_id,- common_enums::ConnectorType::PaymentProcessor,- );+ .filter_by_connector_type(common_enums::ConnectorType::PaymentProcessor);let connector_and_supporting_payment_method_type = filtered_connector_accounts.get_connector_and_supporting_payment_method_type_for_session_call();diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 7b5f684f32..b3b0789ba3 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -2080,9 +2080,9 @@ pub async fn refresh_cgraph_cache() -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {let mut merchant_connector_accounts = state.store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(&key_store.merchant_id,- false,+ profile_id,).await.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;@@ -2115,8 +2115,8 @@ pub async fn refresh_cgraph_cache(}};- let merchant_connector_accounts = merchant_connector_accounts- .filter_based_on_profile_and_connector_type(profile_id, connector_type);+ let merchant_connector_accounts =+ merchant_connector_accounts.filter_by_connector_type(connector_type);let api_mcas = merchant_connector_accounts.into_iter()@@ -2337,7 +2337,7 @@ pub async fn perform_eligibility_analysis(routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,};- let active_mca_ids = get_active_mca_ids(state, key_store).await?;+ let active_mca_ids = get_active_mca_ids(state, key_store, profile_id).await?;perform_cgraph_filtering(state,key_store,@@ -2387,7 +2387,7 @@ pub async fn perform_fallback_routing(#[cfg(feature = "payouts")]routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,};- let active_mca_ids = get_active_mca_ids(state, key_store).await?;+ let active_mca_ids = get_active_mca_ids(state, key_store, business_profile.get_id()).await?;perform_cgraph_filtering(state,key_store,@@ -2539,7 +2539,7 @@ pub async fn perform_session_flow_routing<'a>(api_enums::PaymentMethodType,Vec<routing_types::SessionRoutingChoice>,> = FxHashMap::default();- let active_mca_ids = get_active_mca_ids(state, key_store).await?;+ let active_mca_ids = get_active_mca_ids(state, key_store, &profile_id).await?;for (pm_type, allowed_connectors) in pm_type_map {let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;@@ -2703,7 +2703,8 @@ pub async fn perform_session_flow_routing(Vec<routing_types::SessionRoutingChoice>,> = FxHashMap::default();let mut final_routing_approach = None;- let active_mca_ids = get_active_mca_ids(session_input.state, session_input.key_store).await?;+ let active_mca_ids =+ get_active_mca_ids(session_input.state, session_input.key_store, &profile_id).await?;for (pm_type, allowed_connectors) in pm_type_map {let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;@@ -4087,12 +4088,13 @@ wherepub async fn get_active_mca_ids(state: &SessionState,key_store: &domain::MerchantKeyStore,+ profile_id: &common_utils::id_type::ProfileId,) -> RoutingResult<std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>> {let db_mcas = state.store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(&key_store.merchant_id,- false,+ profile_id,).await.unwrap_or_else(|_| {diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rsindex 168e6d6934..7a86d87170 100644--- a/crates/router/src/core/payout_link.rs+++ b/crates/router/src/core/payout_link.rs@@ -337,17 +337,14 @@ pub async fn filter_payout_methods(let db = &*state.store;//Fetch all merchant connector accountslet all_mcas = db- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),- false,+ &payout.profile_id,).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- // Filter MCAs based on profile_id and connector_type- let filtered_mcas = all_mcas.filter_based_on_profile_and_connector_type(- &payout.profile_id,- common_enums::ConnectorType::PayoutProcessor,- );+ let filtered_mcas =+ all_mcas.filter_by_connector_type(common_enums::ConnectorType::PayoutProcessor);let mut response: Vec<link_utils::EnabledPaymentMethod> = vec![];let mut payment_method_list_hm: HashMap<diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rsindex 4aa331caa4..f790f553fb 100644--- a/crates/router/src/core/routing.rs+++ b/crates/router/src/core/routing.rs@@ -357,11 +357,13 @@ pub async fn create_routing_algorithm_under_profile(.get_required_value("Profile")?;let processor_merchant_id = processor.get_account().get_id();core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;+ // Fetching disabled MCAs too: routing configs may reference MCAs that are+ // temporarily disabled — validation checks connector existence, not activity.let all_mcas = state.store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(processor_merchant_id,- true,+ business_profile.get_id(),).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {@@ -369,14 +371,14 @@ pub async fn create_routing_algorithm_under_profile(})?;let name_mca_id_set = helpers::ConnectNameAndMCAIdForProfile(- all_mcas.filter_by_profile(business_profile.get_id(), |mca| {- (&mca.connector_name, mca.get_id())- }),+ all_mcas+ .iter()+ .map(|mca| (&mca.connector_name, mca.get_id()))+ .collect(),);- let name_set = helpers::ConnectNameForProfile(- all_mcas.filter_by_profile(business_profile.get_id(), |mca| &mca.connector_name),- );+ let name_set =+ helpers::ConnectNameForProfile(all_mcas.iter().map(|mca| &mca.connector_name).collect());let algorithm_helper = helpers::RoutingAlgorithmHelpers {name_mca_id_set,diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rsindex 8942b24dae..def27431ca 100644--- a/crates/router/src/core/routing/helpers.rs+++ b/crates/router/src/core/routing/helpers.rs@@ -472,25 +472,22 @@ pub async fn validate_connectors_in_routing_config(profile_id: &id_type::ProfileId,routing_algorithm: &routing_types::StaticRoutingAlgorithm,) -> RouterResult<()> {+ // Fetching disabled MCAs too: routing configs may reference MCAs that are+ // temporarily disabled — validation checks connector existence, not activity.let all_mcas = state.store- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(- merchant_id,- true,- )+ .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: merchant_id.get_string_repr().to_owned(),})?;let name_mca_id_set = all_mcas.iter()- .filter(|mca| mca.profile_id == *profile_id).map(|mca| (&mca.connector_name, mca.get_id())).collect::<FxHashSet<_>>();let name_set = all_mcas.iter()- .filter(|mca| mca.profile_id == *profile_id).map(|mca| &mca.connector_name).collect::<FxHashSet<_>>();diff --git a/crates/router/src/core/superposition_sdk_config.rs b/crates/router/src/core/superposition_sdk_config.rsindex 4d5d5601c7..27becde761 100644--- a/crates/router/src/core/superposition_sdk_config.rs+++ b/crates/router/src/core/superposition_sdk_config.rs@@ -152,19 +152,14 @@ pub async fn get_profile_superposition_sdk_config(id: profile_id.to_owned(),})?;- let all_mcas = db- .find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(+ let mcas = db+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),- false,+ &profile_id_typed,).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let filtered_mcas: Vec<_> = all_mcas- .into_iter()- .filter(|mca| mca.profile_id == profile_id_typed)- .collect();-let mut payment_experiences_consolidated_hm: std::collections::HashMap<api_enums::PaymentMethod,std::collections::HashMap<@@ -194,7 +189,7 @@ pub async fn get_profile_superposition_sdk_config(Vec<String>,> = std::collections::HashMap::new();- for mca in &filtered_mcas {+ for mca in &mcas {if let Some(payment_methods_enabled_list) = &mca.payment_methods_enabled {for pm_value in payment_methods_enabled_list {if let Ok(pm_enabled) = serde_json::from_value::<@@ -300,8 +295,7 @@ pub async fn get_profile_superposition_sdk_config(dimension_filter.insert("connector".to_string(),serde_json::Value::Array(- filtered_mcas- .iter()+ mcas.iter().map(|mca| serde_json::Value::String(mca.connector_name.clone())).collect(),),diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex c56423fbc7..cb8163249e 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -1562,6 +1562,29 @@ impl MerchantConnectorAccountInterface for KafkaStore {.await}+ async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ &self,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, errors::StorageError> {+ self.diesel_store+ .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id)+ .await+ }++ async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ &self,+ merchant_id: &id_type::MerchantId,+ profile_id: &id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, errors::StorageError> {+ self.diesel_store+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ merchant_id,+ profile_id,+ )+ .await+ }+#[cfg(all(feature = "olap", feature = "v2"))]async fn list_connector_account_by_profile_id(&self,diff --git a/crates/storage_impl/src/merchant_connector_account.rs b/crates/storage_impl/src/merchant_connector_account.rsindex 41fe26ded2..3b39058cf2 100644--- a/crates/storage_impl/src/merchant_connector_account.rs+++ b/crates/storage_impl/src/merchant_connector_account.rs@@ -152,6 +152,31 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for kv_router_store::KV.await}+ #[instrument(skip_all)]+ async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, Self::Error> {+ self.router_store+ .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id)+ .await+ }++ #[instrument(skip_all)]+ async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, Self::Error> {+ self.router_store+ .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ merchant_id,+ profile_id,+ )+ .await+ }+#[instrument(skip_all)]#[cfg(all(feature = "olap", feature = "v2"))]async fn list_connector_account_by_profile_id(@@ -611,6 +636,58 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {))}+ #[instrument(skip_all)]+ async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, Self::Error> {+ let conn = pg_accounts_connection_read(self).await?;+ let items = storage::MerchantConnectorAccount::list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ &conn,+ merchant_id,+ profile_id,+ )+ .await+ .map_err(|error| report!(Self::Error::from(error)))?;++ let output = items+ .into_iter()+ .map(domain::MerchantConnectorAccountWithoutEncrypted::try_from)+ .collect::<Result<Vec<_>, _>>()+ .change_context(Self::Error::DecryptionError)?;++ Ok(domain::MerchantConnectorAccountsWithoutEncrypted::new(+ output,+ ))+ }++ #[instrument(skip_all)]+ async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, Self::Error> {+ let conn = pg_accounts_connection_read(self).await?;+ let items = storage::MerchantConnectorAccount::list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ &conn,+ merchant_id,+ profile_id,+ )+ .await+ .map_err(|error| report!(Self::Error::from(error)))?;++ let output = items+ .into_iter()+ .map(domain::MerchantConnectorAccountWithoutEncrypted::try_from)+ .collect::<Result<Vec<_>, _>>()+ .change_context(Self::Error::DecryptionError)?;++ Ok(domain::MerchantConnectorAccountsWithoutEncrypted::new(+ output,+ ))+ }+#[instrument(skip_all)]#[cfg(all(feature = "olap", feature = "v2"))]async fn list_connector_account_by_profile_id(@@ -1423,6 +1500,72 @@ impl MerchantConnectorAccountInterface for MockDb {))}+ async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, StorageError> {+ let accounts = self+ .merchant_connector_accounts+ .lock()+ .await+ .iter()+ .filter(|account: &&storage::MerchantConnectorAccount| {+ #[cfg(feature = "v1")]+ let profile_matches = account.profile_id.as_ref() == Some(profile_id);+ #[cfg(feature = "v2")]+ let profile_matches = account.profile_id == *profile_id;++ account.merchant_id == *merchant_id && profile_matches+ })+ .cloned()+ .collect::<Vec<storage::MerchantConnectorAccount>>();++ let output = accounts+ .into_iter()+ .map(domain::MerchantConnectorAccountWithoutEncrypted::try_from)+ .collect::<Result<Vec<_>, _>>()+ .change_context(StorageError::DecryptionError)?;++ Ok(domain::MerchantConnectorAccountsWithoutEncrypted::new(+ output,+ ))+ }++ async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> CustomResult<domain::MerchantConnectorAccountsWithoutEncrypted, StorageError> {+ let accounts = self+ .merchant_connector_accounts+ .lock()+ .await+ .iter()+ .filter(|account: &&storage::MerchantConnectorAccount| {+ #[cfg(feature = "v1")]+ let profile_matches = account.profile_id.as_ref() == Some(profile_id);+ #[cfg(feature = "v2")]+ let profile_matches = account.profile_id == *profile_id;++ account.merchant_id == *merchant_id+ && profile_matches+ && account.disabled == Some(false)+ })+ .cloned()+ .collect::<Vec<storage::MerchantConnectorAccount>>();++ let output = accounts+ .into_iter()+ .map(domain::MerchantConnectorAccountWithoutEncrypted::try_from)+ .collect::<Result<Vec<_>, _>>()+ .change_context(StorageError::DecryptionError)?;++ Ok(domain::MerchantConnectorAccountsWithoutEncrypted::new(+ output,+ ))+ }+#[cfg(all(feature = "olap", feature = "v2"))]async fn list_connector_account_by_profile_id(&self,diff --git a/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/down.sql b/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/down.sqlnew file mode 100644index 0000000000..a689bfdeba--- /dev/null+++ b/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS merchant_connector_account_merchant_id_profile_id_index;diff --git a/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/metadata.toml b/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/up.sql b/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/up.sqlnew file mode 100644index 0000000000..ff1451718b--- /dev/null+++ b/migrations/2026-07-29-000001_add_composite_index_merchant_id_profile_id_on_mca/up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS merchant_connector_account_merchant_id_profile_id_index ON merchant_connector_account (merchant_id, profile_id);\ No newline at end of filediff --git a/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/down.sql b/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/down.sqlnew file mode 100644index 0000000000..a541d22ad2--- /dev/null+++ b/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/down.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS merchant_connector_account_merchant_id_index ON merchant_connector_account (merchant_id);diff --git a/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/metadata.toml b/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/up.sql b/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/up.sqlnew file mode 100644index 0000000000..9d3fc2524e--- /dev/null+++ b/migrations/2026-07-29-000002_drop_index_merchant_id_on_mca/up.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS merchant_connector_account_merchant_id_index;