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): pass merchant connector accounts to routing functions (#14666)
Gaurav Rawatc70c4fca411d
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex bfdd972a0f..5f4883dcf4 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -56,10 +56,7 @@ use diesel_models::{fraud_check::FraudCheck, refund as diesel_refund};use error_stack::{report, ResultExt};use euclid::backend::inputs as dsl_inputs;use events::EventInfo;-use futures::{- future::{join_all, BoxFuture},- FutureExt,-};+use futures::future::join_all;use helpers::{decrypt_paze_token, ApplePayData};#[cfg(feature = "v2")]use hyperswitch_domain_models::payments::{@@ -12339,90 +12336,120 @@ wherelet txn = TransactionData::Payment(transaction_data.clone());let txn_data = transaction_data.clone();let fallback = fallback_config.clone();- let state_ref = &state;let fallback_outcome = (fallback.clone(),common_enums::RoutingApproach::DefaultFallback,true,);- let routing_future: BoxFuture<- '_,- Option<(- Vec<api_models::routing::RoutableConnectorChoice>,- common_enums::RoutingApproach,- bool,- )>,- > = straight_through_routing_stage- .map(|stage| {- async move {- stage- .route(StraightThroughRoutingInput { creds_identifier })- .await- .inspect_err(|err| {- logger::error!(error=?err, "straight-through routing failed");- })- .ok()- .map(|out| {- (- out.connectors.connectors,- stage.routing_approach(),- out.check_eligibility,- )- })- }- .boxed()- })- .unwrap_or_else(|| {- async move {- static_dynamic_routing_v1_for_payments(- state_ref,- processor.get_key_store(),- dimensions,- business_profile,- txn_data,- backend_input,- fallback.clone(),- preferred_connector,+ let has_straight_through_routing = straight_through_routing_stage.is_some();+ let straight_through_outcome = if let Some(stage) = straight_through_routing_stage {+ stage+ .route(StraightThroughRoutingInput { creds_identifier })+ .await+ .inspect_err(|err| {+ logger::error!(error=?err, "straight-through routing failed");+ })+ .ok()+ .map(|out| {+ (+ out.connectors.connectors,+ stage.routing_approach(),+ out.check_eligibility,)- .await- .inspect_err(|err| {- logger::error!(error=?err, "static/dynamic routing failed");- })- .ok()- .map(|out| {- (- out.connectors,- out.routing_approach,- out.requires_eligibility,- )- })- }- .boxed()- });+ })+ } else {+ None+ };- let (connectors, routing_approach, requires_eligibility) =- routing_future.await.unwrap_or(fallback_outcome);+ let needs_mca_eligibility = straight_through_outcome+ .as_ref()+ .map(|(_, _, requires_eligibility)| *requires_eligibility)+ .unwrap_or(true);+ let active_mca_ids = if needs_mca_eligibility {+ Some(+ routing::get_active_merchant_connector_accounts(+ &state,+ processor.get_key_store(),+ business_profile.get_id(),+ )+ .await+ .map(|accounts| accounts.get_ids()),+ )+ } else {+ None+ };- let final_connectors = if requires_eligibility {- routing::perform_eligibility_analysis_with_fallback(+ let routing_outcome = if has_straight_through_routing {+ straight_through_outcome+ } else {+ let outcome = static_dynamic_routing_v1_for_payments(&state,processor.get_key_store(),- connectors.clone(),- &txn,- eligible_connectors.clone(),+ dimensions,business_profile,+ txn_data,+ backend_input,+ fallback,+ preferred_connector,+ active_mca_ids+ .as_ref()+ .and_then(|result| result.as_ref().ok()),).await.inspect_err(|err| {- logger::error!(- error = ?err,- "euclid: eligibility analysis failed, using fallback connectors"- );+ logger::error!(error=?err, "static/dynamic routing failed");})- .unwrap_or_else(|_| fallback_config.clone())- } else {- connectors+ .ok()+ .map(|out| {+ (+ out.connectors,+ out.routing_approach,+ out.requires_eligibility,+ )+ });+ outcome+ };++ let (connectors, routing_approach, requires_eligibility) =+ routing_outcome.unwrap_or(fallback_outcome);++ let final_connectors = match active_mca_ids {+ Some(ids_result) if requires_eligibility => {+ let eligibility_result = match ids_result {+ Ok(ids) => {+ routing::perform_eligibility_analysis_with_fallback(+ &state,+ processor.get_key_store(),+ connectors.clone(),+ &txn,+ eligible_connectors.clone(),+ business_profile,+ Some(&ids),+ )+ .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(+ &state,+ &txn,+ eligible_connectors.clone(),+ business_profile,+ )+ .await+ }+ };+ eligibility_result+ .inspect_err(|err| {+ logger::error!(+ error = ?err,+ "euclid: eligibility analysis failed, using fallback connectors"+ );+ })+ .unwrap_or_else(|_| fallback_config.clone())+ }+ _ => connectors,};core_routing::log_connectors("eligibility", &final_connectors);@@ -13381,6 +13408,7 @@ pub async fn route_connector_v2_for_payments(&TransactionData::Payment(transaction_data),None,business_profile,+ None,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -13413,6 +13441,7 @@ pub async fn static_dynamic_routing_v1_for_payments(backend_input: euclid::backend::BackendInput,fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,preferred_connector: Option<String>,+ active_mca_ids: Option<&HashSet<id_type::MerchantConnectorAccountId>>,) -> RouterResult<routing::RoutingConnectorOutcomeWithApproachAndEligibility> {let (static_connectors, static_approach) = routing::perform_static_routing_locally(state,@@ -13423,19 +13452,24 @@ pub async fn static_dynamic_routing_v1_for_payments().await?;- let (connectors, routing_approach) = routing::perform_hybrid_routing_if_enabled(- state,- key_store,- business_profile,- dimensions,- &payment_dsl_input,- &backend_input,- &fallback_config,- &static_connectors,- static_approach,- preferred_connector,- )- .await;+ let (connectors, routing_approach) = if let Some(active_mca_ids) = active_mca_ids {+ routing::perform_hybrid_routing_if_enabled(+ state,+ key_store,+ business_profile,+ dimensions,+ &payment_dsl_input,+ &backend_input,+ &fallback_config,+ &static_connectors,+ static_approach,+ preferred_connector,+ active_mca_ids,+ )+ .await+ } else {+ (static_connectors, static_approach)+ };Ok(routing::RoutingConnectorOutcomeWithApproachAndEligibility {connectors,@@ -13499,6 +13533,7 @@ pub async fn route_connector_v1_for_payouts(&TransactionData::Payout(transaction_data),eligible_connectors,business_profile,+ None,).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex edb8d1457c..bb3d21ce07 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -1738,6 +1738,7 @@ pub async fn perform_hybrid_routing_if_enabled(static_connectors: &[routing_types::RoutableConnectorChoice],static_approach: common_enums::RoutingApproach,preferred_connector: Option<String>,+ active_mca_ids: &std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,) -> (Vec<routing_types::RoutableConnectorChoice>,common_enums::RoutingApproach,@@ -1771,6 +1772,7 @@ pub async fn perform_hybrid_routing_if_enabled(fallback_config,&routing::TransactionData::Payment(payment_dsl_input.clone()),business_profile,+ active_mca_ids,).await.inspect_err(|error| {@@ -2638,7 +2640,7 @@ fn update_eligible_connectors_for_installments(.or(installment_supported_connectors)}-/// Filters active fallbacks by payment eligibility while preserving their configured order.+/// Filters fallbacks using the active MCA IDs fetched by the payment-routing caller.#[cfg(feature = "v1")]pub async fn filter_fallback_based_on_eligibility(state: &SessionState,@@ -2646,19 +2648,15 @@ pub async fn filter_fallback_based_on_eligibility(fallback_config: &[routing_types::RoutableConnectorChoice],transaction_data: &routing::TransactionData<'_>,business_profile: &domain::Profile,+ active_mca_ids: &std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {- let active_mca_ids =- get_active_merchant_connector_accounts(state, key_store, business_profile.get_id())- .await?- .get_ids();-perform_eligibility_analysis(state,key_store,fallback_config.to_vec(),transaction_data,None,- &active_mca_ids,+ active_mca_ids,business_profile,).await@@ -2763,6 +2761,26 @@ pub async fn perform_fallback_routing(.await}+pub(super) async fn get_eligibility_fallback_config(+ state: &SessionState,+ transaction_data: &routing::TransactionData<'_>,+ eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,+ business_profile: &domain::Profile,+) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {+ #[cfg(feature = "v1")]+ let eligible_connectors =+ update_eligible_connectors_for_installments(state, transaction_data, eligible_connectors);+ get_fallback_config(state, transaction_data, business_profile)+ .await+ .map(|mut fallback| {+ if let Some(eligible) = eligible_connectors {+ fallback.retain(|choice| eligible.contains(&choice.connector));+ }+ fallback+ })+}++#[allow(clippy::too_many_arguments)]pub async fn perform_eligibility_analysis_with_fallback(state: &SessionState,key_store: &domain::MerchantKeyStore,@@ -2770,6 +2788,9 @@ pub async fn perform_eligibility_analysis_with_fallback(transaction_data: &routing::TransactionData<'_>,eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,business_profile: &domain::Profile,+ fetched_mca_ids: Option<+ &std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,+ >,) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {logger::debug!("euclid_routing: performing eligibility");@@ -2784,27 +2805,39 @@ pub async fn perform_eligibility_analysis_with_fallback(// swapped for an arbitrary default. Hard failure can still occur downstream (e.g. a// cold-cache refresh errors after this fetch succeeded); only the MCA-fetch failure// is degraded here. Never populate the cgraph cache from a failed fetch.- let active_mca_ids =- match get_active_merchant_connector_accounts(state, key_store, business_profile.get_id())+ let fetched_ids;+ let active_mca_ids = match fetched_mca_ids {+ Some(ids) => ids,+ None => {+ fetched_ids = match get_active_merchant_connector_accounts(+ state,+ key_store,+ business_profile.get_id(),+ ).await- {- 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)- .await- .map(|mut fallback_config| {- if let Some(eligible) = eligible_connectors {- fallback_config.retain(|choice| eligible.contains(&choice.connector));- }- fallback_config- });- }- };+ {+ 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)+ .await+ .map(|mut fallback_config| {+ if let Some(eligible) = eligible_connectors {+ fallback_config+ .retain(|choice| eligible.contains(&choice.connector));+ }+ fallback_config+ });+ }+ };++ &fetched_ids+ }+ };let mut final_selection = perform_eligibility_analysis(state,@@ -2812,18 +2845,17 @@ pub async fn perform_eligibility_analysis_with_fallback(chosen,transaction_data,eligible_connectors.as_ref(),- &active_mca_ids,+ active_mca_ids,business_profile,).await?;-let fallback_selection = perform_fallback_routing(state,key_store,transaction_data,eligible_connectors.as_ref(),business_profile,- &active_mca_ids,+ active_mca_ids,).await;diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex 2152e954ca..2a355a706d 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -1119,6 +1119,7 @@ pub async fn decide_payout_connector(&TransactionData::Payout(payout_data),eligible_connectors,&business_profile,+ None,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -1168,6 +1169,7 @@ pub async fn decide_payout_connector(&TransactionData::Payout(payout_data),eligible_connectors,&business_profile,+ None,).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rsindex 8d9cebceec..6d6f0f4b3b 100644--- a/crates/router/src/core/routing.rs+++ b/crates/router/src/core/routing.rs@@ -3314,6 +3314,7 @@ impl RoutableConnectors {&TransactionData::Payment(payments_dsl_input),None,business_profile,+ None,).await.change_context(errors::ApiErrorResponse::InternalServerError)