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(routing): validate eligibility per merchant connector account (#14895)
Prajjwal Kumaref9e8b9c697b
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 6c995cac6a..1df43ec884 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -6631,7 +6631,10 @@ fn apply_auto_fallback_capture_method<F, D>(let applied = if should_fall_back {logger::info!(payment_id = ?attempt.payment_id,- connector = %connector.connector_name,+ connector = %core_routing::format_connector_for_logging(+ connector.connector_name,+ connector.merchant_connector_id.as_ref(),+ ),payment_method_type = ?attempt.payment_method_type,%requested,%fallback,@@ -12446,20 +12449,30 @@ where.await}Err(error) => {- logger::error!(error=?error, "euclid_routing: failed to fetch active merchant connector accounts; degrading to fallback config");- routing::get_eligibility_fallback_config(+ let fallback = routing::get_eligibility_fallback_config(&state,&txn,eligible_connectors.clone(),business_profile,)- .await+ .await;+ logger::error!(+ error = ?error,+ profile_id = %business_profile.get_id().get_string_repr(),+ eligibility_bypassed = true,+ fallback_connectors = ?fallback.as_ref().ok().map(|connectors| core_routing::format_connectors_for_logging(connectors)),+ "euclid_routing: failed to fetch active merchant connector accounts; degrading to fallback config"+ );+ fallback}};eligibility_result.inspect_err(|err| {logger::error!(error = ?err,+ profile_id = %business_profile.get_id().get_string_repr(),+ eligibility_bypassed = true,+ fallback_connectors = ?core_routing::format_connectors_for_logging(&fallback_config),"euclid: eligibility analysis failed, using fallback connectors");})diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 38360fb9d3..19c63bb7d6 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -140,6 +140,11 @@ type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;type SessionRoutingConnectorKey = Option<common_utils::id_type::MerchantConnectorAccountId>;+type MerchantConnectorGraphs = HashMap<+ common_utils::id_type::MerchantConnectorAccountId,+ hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>,+>;+#[cfg(feature = "v1")]#[derive(Debug, serde::Serialize, serde::Deserialize)]#[serde(untagged)]@@ -1387,9 +1392,13 @@ wherecontinue;}+ let connector_label = routing::format_connector_for_logging(+ choice.connector,+ choice.merchant_connector_id.as_ref(),+ );if !Connector::from(choice.connector).is_separate_authentication_supported() {logger::warn!(- connector = %choice.connector,+ connector = %connector_label,"euclid: skipping retry candidate that does not support external 3ds authentication");continue;@@ -1404,7 +1413,7 @@ whereOk(connector_data) => ordered.push(connector_data.into()),Err(err) => logger::warn!(error = ?err,- connector = %choice.connector,+ connector = %connector_label,"euclid: skipping invalid retry candidate while expanding external-3ds retry list"),}@@ -2317,7 +2326,7 @@ pub async fn get_merchant_cgraph(key_store: &domain::MerchantKeyStore,profile_id: &common_utils::id_type::ProfileId,transaction_type: &api_enums::TransactionType,-) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {+) -> RoutingResult<Arc<MerchantConnectorGraphs>> {let merchant_id = &key_store.merchant_id;let key = {@@ -2347,12 +2356,10 @@ pub async fn get_merchant_cgraph(.store.caches().cgraph- .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>(- CacheKey {- key: key.clone(),- prefix: state.tenant.redis_key_prefix.clone(),- },- )+ .get_val::<Arc<MerchantConnectorGraphs>>(CacheKey {+ key: key.clone(),+ prefix: state.tenant.redis_key_prefix.clone(),+ }).await;let cgraph = if let Some(graph) = cached_cgraph {@@ -2371,7 +2378,7 @@ pub async fn refresh_cgraph_cache(key: String,profile_id: &common_utils::id_type::ProfileId,transaction_type: &api_enums::TransactionType,-) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {+) -> RoutingResult<Arc<MerchantConnectorGraphs>> {// Fetch the MCA list from the DB here (only reached on a cache miss) rather than// reusing a caller-supplied snapshot, so the cached graph is always built from// live data and cannot be poisoned by a stale pre-eviction snapshot.@@ -2417,7 +2424,10 @@ pub async fn refresh_cgraph_cache(let api_mcas = merchant_connector_accounts.into_iter()- .map(admin_api::MCACGraphData::foreign_try_from)+ .map(|mca| {+ let id = mca.get_id();+ admin_api::MCACGraphData::foreign_try_from(mca).map(|graph_data| (id, graph_data))+ }).collect::<Result<Vec<_>, _>>().change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;let connector_configs = state@@ -2431,7 +2441,7 @@ pub async fn refresh_cgraph_cache(let key = api_enums::RoutableConnectors::from_str(&key).map_err(|error| {logger::error!(error=?error,- connector_name = %key,+ connector = %routing::format_connector_for_logging(&key, None),"euclid: invalid connector name in pm_filters config");errors::RoutingError::InvalidConnectorName(key)@@ -2451,11 +2461,10 @@ pub async fn refresh_cgraph_cache(connector_configs,default_configs,};- let cgraph = Arc::new(- mca_graph::make_mca_graph(api_mcas, &config_pm_filters)- .change_context(errors::RoutingError::KgraphCacheRefreshFailed)- .attach_printable("when construction cgraph")?,- );+ let cgraph = Arc::new(build_merchant_connector_graphs(+ api_mcas,+ &config_pm_filters,+ )?);state.store@@ -2473,6 +2482,25 @@ pub async fn refresh_cgraph_cache(Ok(cgraph)}+fn build_merchant_connector_graphs(+ accounts: Vec<(+ common_utils::id_type::MerchantConnectorAccountId,+ admin_api::MCACGraphData,+ )>,+ config: &CountryCurrencyFilter,+) -> RoutingResult<MerchantConnectorGraphs> {+ accounts+ .into_iter()+ .map(|(id, account)| {+ // Separate graphs prevent one MCA from inheriting a sibling's payment methods.+ mca_graph::make_mca_graph(vec![account], config)+ .map(|graph| (id, graph))+ .change_context(errors::RoutingError::KgraphCacheRefreshFailed)+ .attach_printable("when constructing MCA eligibility graph")+ })+ .collect()+}+#[allow(clippy::too_many_arguments)]pub async fn perform_cgraph_filtering(state: &SessionState,@@ -2506,36 +2534,53 @@ pub async fn perform_cgraph_filtering(let cached_cgraph = get_merchant_cgraph(state, key_store, profile_id, transaction_type).await?;+ filter_connector_choices(+ &cached_cgraph,+ chosen,+ &context,+ eligible_connectors,+ active_mca_ids,+ )+}++fn filter_connector_choices(+ graphs: &MerchantConnectorGraphs,+ chosen: Vec<routing_types::RoutableConnectorChoice>,+ context: &euclid_graph::AnalysisContext,+ eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,+ active_mca_ids: &std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,+) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {let mut final_selection = Vec::new();for choice in chosen {- let routable_connector = choice.connector;+ let Some(mca_id) = choice.merchant_connector_id.as_ref() else {+ continue;+ };+ if !active_mca_ids.contains(mca_id)+ || eligible_connectors.is_some_and(|list| !list.contains(&choice.connector))+ {+ continue;+ }+ let Some(cgraph) = graphs.get(mca_id) else {+ continue;+ };let euclid_choice: ast::ConnectorChoice = choice.clone().foreign_into();let dir_val = euclid_choice.into_dir_value().change_context(errors::RoutingError::KgraphAnalysisError)?;- let cgraph_eligible = cached_cgraph+ let cgraph_eligible = cgraph.check_value_validity(dir_val,- &context,+ context,&mut hyperswitch_constraint_graph::Memoization::new(),&mut hyperswitch_constraint_graph::CycleCheck::new(),None,).change_context(errors::RoutingError::KgraphAnalysisError)?;- let filter_eligible =- eligible_connectors.is_none_or(|list| list.contains(&routable_connector));-- let mca_active = choice- .merchant_connector_id- .as_ref()- .map(|id| active_mca_ids.contains(id))- .unwrap_or(false);-- if cgraph_eligible && filter_eligible && mca_active {+ if cgraph_eligible {final_selection.push(choice);}}@@ -2815,12 +2860,7 @@ pub async fn perform_eligibility_analysis_with_fallback({Ok(merchant_connector_accounts) => merchant_connector_accounts.get_ids(),Err(err) => {- logger::error!(- error = ?err,- "euclid_routing: failed to fetch active merchant connector accounts; \- degrading to eligibility-filtered fallback config"- );- return get_fallback_config(state, transaction_data, business_profile)+ let fallback = get_fallback_config(state, transaction_data, business_profile).await.map(|mut fallback_config| {if let Some(eligible) = eligible_connectors {@@ -2829,6 +2869,15 @@ pub async fn perform_eligibility_analysis_with_fallback(}fallback_config});+ logger::error!(+ error = ?err,+ profile_id = %business_profile.get_id().get_string_repr(),+ eligibility_bypassed = true,+ fallback_connectors = ?fallback.as_ref().ok().map(|connectors| routing::format_connectors_for_logging(connectors)),+ "euclid_routing: failed to fetch active merchant connector accounts; \+ degrading to fallback config without MCA eligibility checks"+ );+ return fallback;}};@@ -2867,10 +2916,7 @@ pub async fn perform_eligibility_analysis_with_fallback(.collect::<Vec<_>>(),);- let final_selected_connectors = final_selection- .iter()- .map(|item| item.connector)- .collect::<Vec<_>>();+ let final_selected_connectors = routing::format_connectors_for_logging(&final_selection);logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "euclid_routing: List of final selected connectors for routing");Ok(final_selection)@@ -3592,7 +3638,11 @@ pub async fn perform_dynamic_routing_with_open_router(if let Some(connector) = connectors.connectors.first() {logger::debug!("penalizing the elimination score of the gateway with id {} in open_router for profile {}",- connector, profile.get_id().get_string_repr()+ routing::format_connector_for_logging(+ connector.connector,+ connector.merchant_connector_id.as_ref(),+ ),+ profile.get_id().get_string_repr());update_gateway_score_with_open_router(state,@@ -3971,7 +4021,10 @@ pub async fn update_gateway_score_with_open_router(logger::debug!("open_router update_gateway_score response for gateway with id {}: {:?}",- payment_connector,+ routing::format_connector_for_logging(+ payment_connector.connector,+ payment_connector.merchant_connector_id.as_ref(),+ ),update_score_resp.message);@@ -4173,7 +4226,7 @@ where),});}- logger::debug!(success_based_routing_connectors=?connectors);+ logger::debug!(success_based_routing_connectors=?routing::format_connectors_for_logging(&connectors));routing_event.set_status_code(200);routing_event.set_routable_connectors(connectors.clone());@@ -4367,8 +4420,8 @@ pub async fn perform_elimination_routing(connectors.extend(non_eliminated_connectors.clone());connectors.extend(eliminated_connectors.clone());}- logger::debug!(dynamic_eliminated_connectors=?eliminated_connectors);- logger::debug!(dynamic_elimination_based_routing_connectors=?connectors);+ logger::debug!(dynamic_eliminated_connectors=?routing::format_connectors_for_logging(&eliminated_connectors));+ logger::debug!(dynamic_elimination_based_routing_connectors=?routing::format_connectors_for_logging(&connectors));routing_event.set_status_code(200);routing_event.set_routable_connectors(connectors.clone());@@ -4584,7 +4637,7 @@ whereconnectors.append(&mut other_connectors);- logger::debug!(contract_based_routing_connectors=?connectors);+ logger::debug!(contract_based_routing_connectors=?routing::format_connectors_for_logging(&connectors));routing_event.set_status_code(200);routing_event.set_routable_connectors(connectors.clone());diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rsindex 3964453657..3fcadff34b 100644--- a/crates/router/src/core/payments/routing/utils.rs+++ b/crates/router/src/core/payments/routing/utils.rs@@ -680,7 +680,10 @@ pub async fn perform_decision_euclid_routing(routing_event.set_routable_connectors(euclid_response.evaluated_output.clone());state.event_handler.log_event(&routing_event);- logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid");+ logger::debug!(+ decision_engine_euclid_selected_connector = ?crate::core::routing::format_connectors_for_logging(&euclid_response.evaluated_output),+ "decision_engine_euclid"+ );Ok(euclid_response)}@@ -1794,7 +1797,7 @@ impl TryFrom<ConnectorInfo> for DeRoutableConnectorChoice {.map_err(|error| {logger::error!(error=?error,- gateway_name = %c.gateway_name,+ connector = %crate::core::routing::format_connector_for_logging(&c.gateway_name, gateway_id.as_ref()),"euclid: unable to convert connector name to RoutableConnectors");errors::RoutingError::GenericConversionError {diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rsindex 6d6f0f4b3b..fd0080108e 100644--- a/crates/router/src/core/routing.rs+++ b/crates/router/src/core/routing.rs@@ -3984,10 +3984,34 @@ pub fn transaction_type_from_payments_dsl(input: &PaymentsDslInput<'_>) -> enumsenums::TransactionType::from(&txn_data)}+pub fn format_connector_for_logging(+ connector: impl std::fmt::Display,+ merchant_connector_id: Option<&common_utils::id_type::MerchantConnectorAccountId>,+) -> String {+ format!(+ "{connector}:{}",+ merchant_connector_id+ .map(|id| id.get_string_repr())+ .unwrap_or("<unresolved>")+ )+}++pub fn format_connectors_for_logging(+ connectors: &[routing::RoutableConnectorChoice],+) -> Vec<String> {+ connectors+ .iter()+ .map(|choice| {+ format_connector_for_logging(choice.connector, choice.merchant_connector_id.as_ref())+ })+ .collect()+}+pub fn log_connectors(stage: &str, connectors: &[routing::RoutableConnectorChoice]) {- let names: Vec<String> = connectors.iter().map(|c| c.connector.to_string()).collect();+ let names = format_connectors_for_logging(connectors);router_env::logger::debug!(+ connectors = ?names,"euclid: connectors after {} = {{{}}}",stage,names.join(", ")diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rsindex e421637d8a..1a28af592b 100644--- a/crates/router/src/core/routing/helpers.rs+++ b/crates/router/src/core/routing/helpers.rs@@ -865,7 +865,7 @@ pub async fn update_gateway_score_helper_with_open_router(logger::debug!("decision_engine: performing update-gateway-score for gateway with id {} in open_router for profile: {}",- routable_connector,+ routing::format_connector_for_logging(routable_connector.connector, routable_connector.merchant_connector_id.as_ref()),profile_id.get_string_repr());routing::payments_routing::update_gateway_score_with_open_router(@@ -1505,8 +1505,10 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing()?;logger::debug!(- "contract based routing: matched LabelInformation - {:?}",- final_label_info+ connector = %routing::format_connector_for_logging(payment_connector, Some(&final_label_info.mca_id)),+ target_count = final_label_info.target_count,+ target_time = final_label_info.target_time,+ "contract based routing: matched LabelInformation");let request_label_info = routing_types::LabelInformation {