Skip to content

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

refactor(euclid): de-couple static routing from core (#11001)

Prajjwal Kumar74f221248986
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index ab4db50163..5bbd7b5382 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -20,7 +20,7 @@ pub mod vault_session;
#[cfg(feature = "olap")]
use std::collections::HashMap;
use std::{
- collections::HashSet, fmt::Debug, marker::PhantomData, str::FromStr, time::Instant,
+ collections::HashSet, fmt::Debug, marker::PhantomData, str::FromStr, sync::Arc, time::Instant,
vec::IntoIter,
};
@@ -50,7 +50,10 @@ use common_utils::{
use diesel_models::{fraud_check::FraudCheck, refund as diesel_refund};
use error_stack::{report, ResultExt};
use events::EventInfo;
-use futures::future::join_all;
+use futures::{
+ future::{join_all, BoxFuture},
+ FutureExt,
+};
use helpers::{decrypt_paze_token, ApplePayData};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::{
@@ -75,7 +78,7 @@ use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use router_types::transformers::ForeignFrom;
-use routing::RoutingStage;
+use routing::{RoutingStage, StraightThroughRoutingInput, StraightThroughRoutingStage};
use rustc_hash::FxHashMap;
use scheduler::utils as pt_utils;
#[cfg(feature = "v2")]
@@ -743,7 +746,7 @@ where
.apply_three_ds_authentication_strategy(state, &mut payment_data, &business_profile)
.await;
- let connector = get_connector_choice(
+ let connector = choose_connector(
&operation,
state,
&req,
@@ -9057,7 +9060,7 @@ pub async fn get_vault_operation_for_pre_network_tokenization(
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
-pub async fn get_connector_choice<F, Req, D>(
+pub async fn choose_connector<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
state: &SessionState,
req: &Req,
@@ -9096,7 +9099,7 @@ where
}
api::ConnectorChoice::StraightThrough(straight_through) => {
- connector_selection(
+ perform_routing_for_connector_selection(
state,
platform,
business_profile,
@@ -9109,7 +9112,7 @@ where
}
api::ConnectorChoice::Decide => {
- connector_selection(
+ perform_routing_for_connector_selection(
state,
platform,
business_profile,
@@ -9297,7 +9300,7 @@ where
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
-pub async fn connector_selection<F, D>(
+pub async fn perform_routing_for_connector_selection<F, D>(
state: &SessionState,
platform: &domain::Platform,
business_profile: &domain::Profile,
@@ -9545,294 +9548,206 @@ where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
+ // Pre-determined flow
// If the connector was already decided previously, use the same connector
// This is in case of flows like payments_sync, payments_cancel where the successive operations
// with the connector have to be made using the same connector account.
- if let Some(ref connector_name) = payment_data.get_payment_attempt().connector {
- // Connector was already decided previously, use the same connector
- let connector_data = api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- connector_name,
- api::GetToken::Connector,
- payment_data
- .get_payment_attempt()
- .merchant_connector_id
- .clone(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Invalid connector name received in 'routed_through'")?;
-
- routing_data.routed_through = Some(connector_name.clone());
- logger::debug!("euclid_routing: predetermined connector present in attempt");
- return Ok(ConnectorCallType::PreDetermined(connector_data.into()));
- }
-
- if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() {
- let connector_data = api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &mandate_connector_details.connector,
- api::GetToken::Connector,
- mandate_connector_details.merchant_connector_id.clone(),
+ let pre_decided_connector = routing::try_get_pre_determined_connector::<F, D>(
+ &state.conf.connectors,
+ payment_data,
+ routing_data,
+ )
+ .inspect_err(|err| {
+ logger::error!(
+ error = ?err,
+ "euclid: pre-determined connector resolution failed, continuing with routing"
+ );
+ })
+ .ok()
+ .flatten()
+ .or(
+ // Check if pre_routing connector is present
+ routing::try_pre_routing_connectors::<F, D>(
+ &state,
+ platform,
+ business_profile,
+ payment_data,
+ routing_data,
)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Invalid connector name received in 'routed_through'")?;
-
- routing_data.routed_through = Some(mandate_connector_details.connector.clone());
-
- routing_data
- .merchant_connector_id
- .clone_from(&mandate_connector_details.merchant_connector_id);
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ error = ?err,
+ "euclid: pre-routing connector resolution failed, continuing with routing"
+ );
+ })
+ .ok()
+ .flatten(),
+ );
- logger::debug!("euclid_routing: predetermined mandate connector");
- return Ok(ConnectorCallType::PreDetermined(connector_data.into()));
+ if let Some(connector) = pre_decided_connector {
+ return Ok(connector);
}
- if let Some((pre_routing_results, storage_pm_type)) =
- routing_data.routing_info.pre_routing_results.as_ref().zip(
- payment_data
- .get_payment_attempt()
- .payment_method_type
- .as_ref(),
- )
- {
- if let (Some(routable_connector_choice), None) = (
- pre_routing_results.get(storage_pm_type),
- &payment_data.get_token_data(),
- ) {
- let routable_connector_list = match routable_connector_choice {
- storage::PreRoutingConnectorChoice::Single(routable_connector) => {
- vec![routable_connector.clone()]
- }
- storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
- routable_connector_list.clone()
- }
- };
+ let transaction_data = core_routing::PaymentsDslInput::new(
+ payment_data.get_setup_mandate(),
+ payment_data.get_payment_attempt(),
+ payment_data.get_payment_intent(),
+ payment_data.get_payment_method_data(),
+ payment_data.get_address(),
+ payment_data.get_recurring_details(),
+ payment_data.get_currency(),
+ );
- let mut pre_routing_connector_data_list = vec![];
+ let fallback_config = routing_helpers::get_merchant_default_config(
+ &*state.clone().store,
+ business_profile.get_id().get_string_repr(),
+ &transaction_type_from_payments_dsl(&transaction_data),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("euclid: failed to fetch fallback config")?;
- let first_routable_connector = routable_connector_list
- .first()
- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
+ // Straight through routing block
+ let request_straight_through_routing_stage =
+ request_straight_through.map(|algo| StraightThroughRoutingStage {
+ algorithm: Arc::new(algo),
+ });
- routing_data.routed_through = Some(first_routable_connector.connector.to_string());
+ let algorithmic_straight_through_routing_stage = routing_data
+ .routing_info
+ .algorithm
+ .as_ref()
+ .map(|algo| StraightThroughRoutingStage {
+ algorithm: Arc::new(algo.clone()),
+ });
- routing_data
- .merchant_connector_id
- .clone_from(&first_routable_connector.merchant_connector_id);
-
- for connector_choice in routable_connector_list.clone() {
- let connector_data = api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &connector_choice.connector.to_string(),
- api::GetToken::Connector,
- connector_choice.merchant_connector_id.clone(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Invalid connector name received")?
- .into();
+ let straight_through_routing_stage =
+ request_straight_through_routing_stage.or(algorithmic_straight_through_routing_stage);
+
+ let creds_identifier = payment_data.get_creds_identifier();
+ let txn = TransactionData::Payment(transaction_data.clone());
+ let txn_data = transaction_data.clone();
+ let fallback = fallback_config.clone();
+ let eligible = eligible_connectors.clone();
+ let state_ref = &state;
+ let fallback_outcome = (
+ fallback.clone(),
+ common_enums::RoutingApproach::DefaultFallback,
+ true,
+ );
- pre_routing_connector_data_list.push(connector_data);
+ 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,
+ )
+ })
}
-
- #[cfg(feature = "retry")]
- let should_do_retry = retry::config_should_call_gsm(
- &*state.store,
- platform.get_processor().get_account().get_id(),
- business_profile,
- )
- .await;
-
- #[cfg(feature = "retry")]
- if payment_data.get_payment_attempt().payment_method_type
- == Some(storage_enums::PaymentMethodType::ApplePay)
- && should_do_retry
- {
- let retryable_connector_data = helpers::get_apple_pay_retryable_connectors(
- &state,
+ .boxed()
+ })
+ .unwrap_or_else(|| {
+ async move {
+ static_dynamic_routing_v1_for_payments(
+ state_ref,
platform,
- payment_data,
- &pre_routing_connector_data_list,
- first_routable_connector
- .merchant_connector_id
- .clone()
- .as_ref(),
- business_profile.clone(),
+ business_profile,
+ txn_data,
+ eligible,
+ fallback.clone(),
)
- .await?;
-
- if let Some(connector_data_list) = retryable_connector_data {
- if connector_data_list.len() > 1 {
- logger::info!("Constructed apple pay retryable connector list");
- return Ok(ConnectorCallType::Retryable(connector_data_list));
- }
- }
+ .await
+ .inspect_err(|err| {
+ logger::error!(error=?err, "static/dynamic routing failed");
+ })
+ .ok()
+ .map(|out| {
+ (
+ out.connectors,
+ out.routing_approach,
+ out.requires_eligibility,
+ )
+ })
}
+ .boxed()
+ });
- logger::debug!("euclid_routing: pre-routing connector present");
-
- let first_pre_routing_connector_data_list = pre_routing_connector_data_list
- .first()
- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
-
- helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?;
-
- return Ok(ConnectorCallType::PreDetermined(
- first_pre_routing_connector_data_list.clone(),
- ));
- }
- }
-
- if let Some(routing_algorithm) = request_straight_through {
- let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(
- &routing_algorithm,
- payment_data.get_creds_identifier(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed execution of straight through routing")?;
-
- payment_data.set_routing_approach_in_attempt(Some(
- common_enums::RoutingApproach::StraightThroughRouting,
- ));
-
- if check_eligibility {
- let transaction_data = core_routing::PaymentsDslInput::new(
- payment_data.get_setup_mandate(),
- payment_data.get_payment_attempt(),
- payment_data.get_payment_intent(),
- payment_data.get_payment_method_data(),
- payment_data.get_address(),
- payment_data.get_recurring_details(),
- payment_data.get_currency(),
- );
-
- connectors = routing::perform_eligibility_analysis_with_fallback(
- &state.clone(),
- platform.get_processor().get_key_store(),
- connectors,
- &TransactionData::Payment(transaction_data),
- eligible_connectors,
- business_profile,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed eligibility analysis and fallback")?;
- }
-
- let connector_data = connectors
- .into_iter()
- .map(|conn| {
- api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &conn.connector.to_string(),
- api::GetToken::Connector,
- conn.merchant_connector_id.clone(),
- )
- .map(|connector_data| connector_data.into())
- })
- .collect::<CustomResult<Vec<_>, _>>()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Invalid connector name received")?;
+ let (connectors, routing_approach, requires_eligibility) =
+ routing_future.await.unwrap_or(fallback_outcome);
- logger::debug!("euclid_routing: straight through connector present");
- return decide_multiplex_connector_for_normal_or_recurring_payment(
+ let final_connectors = if requires_eligibility {
+ routing::perform_eligibility_analysis_with_fallback(
&state,
- payment_data,
- routing_data,
- connector_data,
- mandate_type,
- business_profile.is_connector_agnostic_mit_enabled,
- business_profile.is_network_tokenization_enabled,
- )
- .await;
- }
-
- if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm {
- let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(
- routing_algorithm,
- payment_data.get_creds_identifier(),
+ platform.get_processor().get_key_store(),
+ connectors.clone(),
+ &txn,
+ eligible_connectors.clone(),
+ business_profile,
)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed execution of straight through routing")?;
-
- if check_eligibility {
- let transaction_data = core_routing::PaymentsDslInput::new(
- payment_data.get_setup_mandate(),
- payment_data.get_payment_attempt(),
- payment_data.get_payment_intent(),
- payment_data.get_payment_method_data(),
- payment_data.get_address(),
- payment_data.get_recurring_details(),
- payment_data.get_currency(),
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ error = ?err,
+ "euclid: eligibility analysis failed, using fallback connectors"
);
+ })
+ .unwrap_or_else(|_| fallback_config.clone())
+ } else {
+ connectors
+ };
- connectors = routing::perform_eligibility_analysis_with_fallback(
- &state,
- platform.get_processor().get_key_store(),
- connectors,
- &TransactionData::Payment(transaction_data),
- eligible_connectors,
- business_profile,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed eligibility analysis and fallback")?;
- }
-
- logger::debug!("euclid_routing: single connector present in algorithm data");
- let connector_data = connectors
- .into_iter()
- .map(|conn| {
- api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &conn.connector.to_string(),
- api::GetToken::Connector,
- conn.merchant_connector_id,
- )
- .map(|connector_data| connector_data.into())
- })
- .collect::<CustomResult<Vec<_>, _>>()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Invalid connector name received")?;
+ core_routing::log_connectors("eligibility", &final_connectors);
- return decide_multiplex_connector_for_normal_or_recurring_payment(
- &state,
- payment_data,
- routing_data,
- connector_data,
- mandate_type,
- business_profile.is_connector_agnostic_mit_enabled,
- business_profile.is_network_tokenization_enabled,
- )
- .await;
- }
+ let connector_data = final_connectors
+ .into_iter()
+ .map(|conn| {
+ api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &conn.connector.to_string(),
+ api::GetToken::Connector,
+ conn.merchant_connector_id,
+ )
+ .map(|connector_data| connector_data.into())
+ })
+ .collect::<CustomResult<Vec<_>, _>>()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("euclid: Invalid connector name received")?;
- let new_pd = payment_data.clone();
- let transaction_data = core_routing::PaymentsDslInput::new(
- new_pd.get_setup_mandate(),
- new_pd.get_payment_attempt(),
- new_pd.get_payment_intent(),
- new_pd.get_payment_method_data(),
- new_pd.get_address(),
- new_pd.get_recurring_details(),
- new_pd.get_currency(),
- );
+ payment_data.set_routing_approach_in_attempt(Some(routing_approach));
- route_connector_v1_for_payments(
+ plan_payment_execution_after_routing(
&state,
- platform,
- business_profile,
payment_data,
- transaction_data,
routing_data,
- eligible_connectors,
+ connector_data,
mandate_type,
+ business_profile.is_connector_agnostic_mit_enabled,
+ business_profile.is_network_tokenization_enabled,
)
.await
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
-pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>(
+pub async fn plan_payment_execution_after_routing<F: Clone, D>(
state: &SessionState,
payment_data: &mut D,
routing_data: &mut storage::RoutingData,
@@ -10587,34 +10502,17 @@ pub async fn route_connector_v2_for_payments(
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
-pub async fn route_connector_v1_for_payments<F, D>(
+pub async fn static_dynamic_routing_v1_for_payments(
state: &SessionState,
platform: &domain::Platform,
business_profile: &domain::Profile,
- payment_data: &mut D,
transaction_data: core_routing::PaymentsDslInput<'_>,
- routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
- mandate_type: Option<api::MandateTransactionType>,
-) -> RouterResult<ConnectorCallType>
-where
- F: Send + Clone,
- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
-{
+ fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,
+) -> RouterResult<routing::RoutingConnectorOutcomeWithApproachAndEligibility> {
let txn_type = transaction_type_from_payments_dsl(&transaction_data);
-
- let fallback_config = routing_helpers::get_merchant_default_config(
- &*state.clone().store,
- business_profile.get_id().get_string_repr(),
- &txn_type,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("euclid: failed to fetch fallback config")?;
-
let routing_algorithm_id = {
let routing_algorithm = business_profile.routing_algorithm.clone();
-
let algorithm_ref = routing_algorithm
.map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef"))
.transpose()
@@ -10721,51 +10619,11 @@ where
#[cfg(not(all(feature = "v1", feature = "dynamic_routing")))]
let (connectors, routing_approach) = (static_connectors, static_approach);
- let routable_connectors = routing::perform_eligibility_analysis_with_fallback(
- state,
- platform.get_processor().get_key_store(),
+ Ok(routing::RoutingConnectorOutcomeWithApproachAndEligibility {
connectors,
- &TransactionData::Payment(transaction_data.clone()),
- eligible_connectors,
- business_profile,
- )
- .await
- .unwrap_or_else(|err| {
- logger::error!(
- error=?err,
- "euclid: eligibility analysis failed, using fallback connectors"
- );
- fallback_config.clone()
- });
-
- core_routing::log_connectors("eligibility", &routable_connectors);
-
- payment_data.set_routing_approach_in_attempt(Some(routing_approach));
- let connector_data = routable_connectors
- .into_iter()
- .map(|conn| {
- api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &conn.connector.to_string(),
- api::GetToken::Connector,
- conn.merchant_connector_id,
- )
- .map(|connector_data| connector_data.into())
- })
- .collect::<CustomResult<Vec<_>, _>>()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("euclid: Invalid connector name received")?;
-
- decide_multiplex_connector_for_normal_or_recurring_payment(
- state,
- payment_data,
- routing_data,
- connector_data,
- mandate_type,
- business_profile.is_connector_agnostic_mit_enabled,
- business_profile.is_network_tokenization_enabled,
- )
- .await
+ routing_approach,
+ requires_eligibility: true,
+ })
}
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index b740030bb4..642dea0faf 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -6266,18 +6266,14 @@ pub fn get_debit_routing_savings_amount(
}
#[cfg(all(feature = "retry", feature = "v1"))]
-pub async fn get_apple_pay_retryable_connectors<F, D>(
+pub async fn get_apple_pay_retryable_connectors(
state: &SessionState,
platform: &domain::Platform,
- payment_data: &D,
+ creds_identifier: Option<&str>,
pre_routing_connector_data_list: &[api::ConnectorRoutingData],
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
business_profile: domain::Profile,
-) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse>
-where
- F: Send + Clone,
- D: OperationSessionGetters<F> + Send,
-{
+) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse> {
let profile_id = business_profile.get_id();
let pre_decided_connector_data_first = pre_routing_connector_data_list
@@ -6287,7 +6283,7 @@ where
let merchant_connector_account_type = get_merchant_connector_account(
state,
platform.get_processor(),
- payment_data.get_creds_identifier(),
+ creds_identifier,
profile_id,
&pre_decided_connector_data_first
.connector_data
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index a62576d936..591ebef393 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -32,7 +32,10 @@ use external_services::grpc_client::dynamic_routing::{
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting, DynamicRoutingError,
};
-use hyperswitch_domain_models::address::Address;
+use hyperswitch_domain_models::{
+ address::Address,
+ routing::{PreRoutingConnectorChoice, RoutingData},
+};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_interfaces::events::routing_api_logs::{ApiMethod, RoutingEngine};
use kgraph_utils::{
@@ -706,6 +709,49 @@ impl RoutingConnectorOutcome {
}
}
+impl From<Vec<routing_types::RoutableConnectorChoice>> for RoutingConnectorOutcome {
+ fn from(connectors: Vec<routing_types::RoutableConnectorChoice>) -> Self {
+ Self { connectors }
+ }
+}
+
+pub struct StraightThroughRoutingStage {
+ pub algorithm: Arc<api_models::routing::StraightThroughAlgorithm>,
+}
+
+pub struct StraightThroughRoutingInput<'a> {
+ pub creds_identifier: Option<&'a str>,
+}
+
+pub struct ConnectorOutcomeWithEligibilityRequirement {
+ pub connectors: RoutingConnectorOutcome,
+ pub check_eligibility: bool,
+}
+
+impl RoutingStage for StraightThroughRoutingStage {
+ type Input<'a> = StraightThroughRoutingInput<'a>;
+ type Output = ConnectorOutcomeWithEligibilityRequirement;
+ type Fut<'a> = BoxFuture<'a, RoutingResult<Self::Output>>;
+
+ fn route<'a>(&'a self, input: Self::Input<'a>) -> Self::Fut<'a> {
+ Box::pin(async move {
+ let (connectors, check_eligibility) =
+ perform_straight_through_routing(&self.algorithm.clone(), input.creds_identifier)
+ .change_context(errors::RoutingError::DslExecutionError)
+ .attach_printable("euclid: unable to perform straight through routing")?;
+
+ Ok(ConnectorOutcomeWithEligibilityRequirement {
+ connectors: connectors.into(),
+ check_eligibility,
+ })
+ })
+ }
+
+ fn routing_approach(&self) -> common_enums::RoutingApproach {
+ common_enums::RoutingApproach::StraightThroughRouting
+ }
+}
+
#[derive(Clone)]
pub struct StaticRoutingInput<'a> {
pub platform: &'a domain::Platform,
@@ -743,9 +789,283 @@ impl RoutingStage for StaticRoutingStage {
}
}
+pub struct RoutingConnectorOutcomeWithApproachAndEligibility {
+ pub connectors: Vec<routing_types::RoutableConnectorChoice>,
+ pub routing_approach: common_enums::RoutingApproach,
+ pub requires_eligibility: bool,
+}
+
+pub struct PreRoutingInput<'a> {
+ pub pre_routing_results:
+ &'a Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>,
+ pub payment_method_type: &'a storage_enums::PaymentMethodType,
+ pub connectors: &'a hyperswitch_interfaces::configs::Connectors,
+ pub platform: &'a domain::Platform,
+ pub business_profile: &'a domain::Profile,
+ pub creds_identifier: Option<&'a str>,
+}
+
+pub async fn resolve_pre_routed_connectors(
+ input: PreRoutingInput<'_>,
+) -> RoutingResult<Vec<api::ConnectorRoutingData>> {
+ let routable_connector_choice = input
+ .pre_routing_results
+ .as_ref()
+ .ok_or(errors::RoutingError::DslExecutionError)?
+ .get(input.payment_method_type)
+ .ok_or(errors::RoutingError::DslExecutionError)?;
+
+ let routable_connectors = match routable_connector_choice {
+ PreRoutingConnectorChoice::Single(c) => vec![c.clone()],
+ PreRoutingConnectorChoice::Multiple(cs) => cs.clone(),
+ };
+
+ let mut connector_routing_data = Vec::with_capacity(routable_connectors.len());
+
+ for connector_choice in routable_connectors {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ input.connectors,
+ &connector_choice.connector.to_string(),
+ api::GetToken::Connector,
+ connector_choice.merchant_connector_id.clone(),
+ )
+ .change_context(errors::RoutingError::DslExecutionError)
+ .attach_printable("Invalid connector name received")?
+ .into();
+
+ connector_routing_data.push(connector_data);
+ }
+ logger::debug!("euclid_routing: pre-routing connectors resolved");
+ Ok(connector_routing_data)
+}
+
+pub fn try_get_attempt_connector<F, D>(
+ connectors: &hyperswitch_interfaces::configs::Connectors,
+ payment_data: &D,
+ routing_data: &mut RoutingData,
+) -> errors::RouterResult<Option<api::ConnectorCallType>>
+where
+ F: Send + Clone,
+ D: OperationSessionGetters<F>,
+{
+ Ok(payment_data
+ .get_payment_attempt()
+ .connector
+ .as_ref()
+ .and_then(|connector_name| {
+ api::ConnectorData::get_connector_by_name(
+ connectors,
+ connector_name,
+ api::GetToken::Connector,
+ payment_data
+ .get_payment_attempt()
+ .merchant_connector_id
+ .clone(),
+ )
+ .inspect_err(|err| {
+ logger::warn!(
+ error=?err,
+ "euclid: invalid predetermined connector, ignoring"
+ );
+ })
+ .ok()
+ .map(|connector_data| {
+ logger::debug!("euclid_routing: predetermined connector present in attempt");
+ routing_data.routed_through = Some(connector_name.clone());
+ api::ConnectorCallType::PreDetermined(connector_data.into())
+ })
+ }))
+}
+
+pub fn try_get_mandate_connector<F, D>(
+ connectors: &hyperswitch_interfaces::configs::Connectors,
+ payment_data: &D,
+ routing_data: &mut RoutingData,
+) -> errors::RouterResult<Option<api::ConnectorCallType>>
+where
+ F: Send + Clone,
+ D: OperationSessionGetters<F>,
+{
+ Ok(payment_data
+ .get_mandate_connector()
+ .and_then(|mandate_connector_details| {
+ api::ConnectorData::get_connector_by_name(
+ connectors,
+ &mandate_connector_details.connector,
+ api::GetToken::Connector,
+ mandate_connector_details.merchant_connector_id.clone(),
+ )
+ .inspect_err(|err| {
+ logger::warn!(
+ error=?err,
+ "euclid: invalid mandate connector, ignoring"
+ );
+ })
+ .ok()
+ .map(|connector_data| {
+ logger::debug!("euclid_routing: predetermined mandate connector");
+ routing_data.routed_through = Some(mandate_connector_details.connector.clone());
+ routing_data
+ .merchant_connector_id
+ .clone_from(&mandate_connector_details.merchant_connector_id);
+ api::ConnectorCallType::PreDetermined(connector_data.into())
+ })
+ }))
+}
+
+pub fn try_get_pre_determined_connector<F, D>(
+ connectors: &hyperswitch_interfaces::configs::Connectors,
+ payment_data: &D,
+ routing_data: &mut RoutingData,
+) -> errors::RouterResult<Option<api::ConnectorCallType>>
+where
+ F: Send + Clone,
+ D: OperationSessionGetters<F>,
+{
+ match try_get_attempt_connector::<F, D>(connectors, payment_data, routing_data)? {
+ Some(connector) => Ok(Some(connector)),
+ None => try_get_mandate_connector::<F, D>(connectors, payment_data, routing_data),
+ }
+}
+
+#[cfg(feature = "v1")]
+pub async fn try_pre_routing_connectors<F, D>(
+ state: &SessionState,
+ platform: &domain::Platform,
+ business_profile: &domain::Profile,
+ payment_data: &mut D,
+ routing_data: &mut RoutingData,
+) -> errors::RouterResult<Option<api::ConnectorCallType>>
+where
+ F: Send + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ let mut connector_call_type = None;
+
+ if let (None, Some(payment_method_type)) = (
+ payment_data.get_token_data(),
+ payment_data
+ .get_payment_attempt()
+ .payment_method_type
+ .as_ref(),
+ ) {
+ logger::debug!("euclid: considering pre-routing result");
+ let pre_routing_input = PreRoutingInput {
+ pre_routing_results: &routing_data.routing_info.pre_routing_results,
+ payment_method_type,
+ connectors: &state.conf.connectors,
+ platform,
+ business_profile,
+ creds_identifier: payment_data.get_creds_identifier(),
+ };
+
+ if let Ok(connectors) = resolve_pre_routed_connectors(pre_routing_input).await {
+ let first_connector = connectors
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
+
+ #[cfg(feature = "retry")]
+ {
+ let should_do_retry = crate::core::payments::retry::config_should_call_gsm(
+ &*state.store,
+ platform.get_processor().get_account().get_id(),
+ business_profile,
+ )
+ .await;
+
+ if payment_data.get_payment_attempt().payment_method_type
+ == Some(storage_enums::PaymentMethodType::ApplePay)
+ && should_do_retry
+ {
+ let retryable_connector_data =
+ crate::core::payments::helpers::get_apple_pay_retryable_connectors(
+ state,
+ platform,
+ payment_data.get_creds_identifier(),
+ &connectors.clone(),
+ first_connector
+ .connector_data
+ .merchant_connector_id
+ .clone()
+ .as_ref(),
+ business_profile.clone(),
+ )
+ .await?;
+
+ if let Some(connector_data_list) = retryable_connector_data {
+ if connector_data_list.len() > 1 {
+ logger::info!("Constructed apple pay retryable connector list");
+ connector_call_type =
+ Some(api::ConnectorCallType::Retryable(connector_data_list));
+ }
+ }
+ }
+ }
+
+ if connector_call_type.is_none() {
+ routing_data.routed_through = Some(
+ first_connector
+ .connector_data
+ .connector_name
+ .to_string()
+ .clone(),
+ );
+
+ routing_data.merchant_connector_id =
+ first_connector.connector_data.merchant_connector_id.clone();
+
+ crate::core::payments::helpers::override_setup_future_usage_to_on_session(
+ &*state.store,
+ payment_data,
+ )
+ .await?;
+
+ connector_call_type = Some(api::ConnectorCallType::PreDetermined(
+ first_connector.clone(),
+ ));
+ }
+ }
+ }
+
+ Ok(connector_call_type)
+}
+
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub struct DynamicRoutingStage;
+pub struct RoutingConnectorOutcomeWithApproach {
+ pub connectors: Vec<routing_types::RoutableConnectorChoice>,
+ pub routing_approach: common_enums::RoutingApproach,
+}
+
+impl RoutingConnectorOutcomeWithApproach {
+ pub fn resolve_or_fallback(
+ self,
+ stage: &'static str,
+ fallback_connectors: &[routing_types::RoutableConnectorChoice],
+ fallback_approach: common_enums::RoutingApproach,
+ ) -> (
+ Vec<routing_types::RoutableConnectorChoice>,
+ common_enums::RoutingApproach,
+ ) {
+ if self.connectors.is_empty() {
+ logger::warn!("euclid: {} returned empty connectors, falling back", stage);
+ routing::log_connectors(stage, fallback_connectors);
+ (fallback_connectors.to_vec(), fallback_approach)
+ } else {
+ routing::log_connectors(stage, &self.connectors);
+ (self.connectors, self.routing_approach)
+ }
+ }
+
+ pub fn empty() -> Self {
+ Self {
+ connectors: Vec::new(),
+ routing_approach: common_enums::RoutingApproach::DefaultFallback,
+ }
+ }
+}
+
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl DynamicRoutingStage {
async fn resolve_dynamic_connectors(
@@ -2119,38 +2439,6 @@ pub fn make_dsl_input_for_surcharge(
Ok(backend_input)
}
-pub struct RoutingConnectorOutcomeWithApproach {
- pub connectors: Vec<routing_types::RoutableConnectorChoice>,
- pub routing_approach: common_enums::RoutingApproach,
-}
-
-impl RoutingConnectorOutcomeWithApproach {
- pub fn resolve_or_fallback(
- self,
- stage: &'static str,
- fallback_connectors: &[routing_types::RoutableConnectorChoice],
- fallback_approach: common_enums::RoutingApproach,
- ) -> (
- Vec<routing_types::RoutableConnectorChoice>,
- common_enums::RoutingApproach,
- ) {
- if self.connectors.is_empty() {
- logger::warn!("euclid: {} returned empty connectors, falling back", stage);
- routing::log_connectors(stage, fallback_connectors);
- (fallback_connectors.to_vec(), fallback_approach)
- } else {
- routing::log_connectors(stage, &self.connectors);
- (self.connectors, self.routing_approach)
- }
- }
-
- pub fn empty() -> Self {
- Self {
- connectors: Vec::new(),
- routing_approach: common_enums::RoutingApproach::DefaultFallback,
- }
- }
-}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_dynamic_routing_with_open_router(
state: &SessionState,