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 sessions routing from core (#11227)

Prajjwal Kumar3c6dadb68974
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 5ebc2d695a..a9716bf6b9 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -49,6 +49,7 @@ use common_utils::{
};
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},
@@ -98,7 +99,6 @@ use self::{
flows::{ConstructFlowSpecificData, Feature},
gateway::context as gateway_context,
operations::{BoxedOperation, Operation, PaymentResponse},
- routing::{self as self_routing, SessionFlowRoutingInput},
};
use super::{
errors::StorageErrorExt,
@@ -9183,54 +9183,97 @@ where
)
.await?;
- let connector = if should_call_connector(operation, payment_data) {
- Some(match connector_choice {
- api::ConnectorChoice::SessionMultiple(connectors) => {
- let routing_output = perform_session_token_routing(
- state.clone(),
- platform,
- business_profile,
- payment_data,
- connectors,
- )
- .await?;
- ConnectorCallType::SessionMultiple(routing_output)
- }
+ 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(),
+ );
- api::ConnectorChoice::StraightThrough(straight_through) => {
- perform_routing_for_connector_selection(
- state,
- platform,
- business_profile,
- payment_data,
- Some(straight_through),
- eligible_connectors,
- mandate_type,
- )
- .await?
- }
+ 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")?;
- api::ConnectorChoice::Decide => {
- perform_routing_for_connector_selection(
- state,
- platform,
- business_profile,
- payment_data,
- None,
- eligible_connectors,
- mandate_type,
- )
- .await?
+ let connector = match routing::make_dsl_input(&transaction_data).inspect_err(|err| {
+ logger::error!(
+ error=?err,
+ "euclid: make_dsl_input failed, falling back"
+ );
+ }) {
+ Ok(backend_input) => {
+ let transaction_type = enums::TransactionType::Payment;
+
+ if should_call_connector(operation, payment_data) {
+ Some(match connector_choice {
+ api::ConnectorChoice::SessionMultiple(connectors) => {
+ let routing_output = perform_session_token_routing(
+ state.clone(),
+ platform,
+ business_profile,
+ payment_data,
+ connectors,
+ fallback_config,
+ backend_input,
+ transaction_type,
+ )
+ .await?;
+ ConnectorCallType::SessionMultiple(routing_output)
+ }
+
+ api::ConnectorChoice::StraightThrough(straight_through) => {
+ perform_routing_for_connector_selection(
+ state,
+ platform,
+ business_profile,
+ payment_data,
+ Some(straight_through),
+ eligible_connectors,
+ mandate_type,
+ fallback_config,
+ backend_input,
+ )
+ .await?
+ }
+
+ api::ConnectorChoice::Decide => {
+ perform_routing_for_connector_selection(
+ state,
+ platform,
+ business_profile,
+ payment_data,
+ None,
+ eligible_connectors,
+ mandate_type,
+ fallback_config,
+ backend_input,
+ )
+ .await?
+ }
+ })
+ } else if let api::ConnectorChoice::StraightThrough(algorithm) = connector_choice {
+ update_straight_through_routing(payment_data, algorithm)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update straight through routing algorithm")?;
+
+ None
+ } else {
+ None
}
- })
- } else if let api::ConnectorChoice::StraightThrough(algorithm) = connector_choice {
- update_straight_through_routing(payment_data, algorithm)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to update straight through routing algorithm")?;
+ }
+ Err(_) => {
+ let fallback_routing_data =
+ core_routing::convert_fallback_to_connector_routing_data(state, &fallback_config)?;
- None
- } else {
- None
+ Some(ConnectorCallType::Retryable(fallback_routing_data))
+ }
};
Ok(connector)
}
@@ -9407,6 +9450,8 @@ pub async fn perform_routing_for_connector_selection<F, D>(
request_straight_through: Option<serde_json::Value>,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
+ fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,
+ backend_input: dsl_inputs::BackendInput,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
@@ -9451,6 +9496,8 @@ where
&mut routing_data,
eligible_connectors,
mandate_type,
+ fallback_config,
+ backend_input,
)
.await?;
@@ -9461,7 +9508,6 @@ where
.attach_printable("error serializing payment routing info to serde value")?;
payment_data.set_connector_in_payment_attempt(routing_data.routed_through);
-
payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id);
payment_data.set_straight_through_algorithm_in_payment_attempt(encoded_info);
@@ -9642,6 +9688,8 @@ pub async fn decide_connector<F, D>(
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
+ fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,
+ backend_input: dsl_inputs::BackendInput,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
@@ -9698,15 +9746,6 @@ where
payment_data.get_currency(),
);
- 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")?;
-
// Straight through routing block
let request_straight_through_routing_stage =
request_straight_through.map(|algo| StraightThroughRoutingStage {
@@ -9728,7 +9767,6 @@ where
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(),
@@ -9767,10 +9805,9 @@ where
async move {
static_dynamic_routing_v1_for_payments(
state_ref,
- platform,
business_profile,
txn_data,
- eligible,
+ backend_input,
fallback.clone(),
)
.await
@@ -10458,43 +10495,72 @@ pub fn should_add_task_to_process_tracker<F: Clone, D: OperationSessionGetters<F
}
#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
pub async fn perform_session_token_routing<F, D>(
state: SessionState,
platform: &domain::Platform,
business_profile: &domain::Profile,
payment_data: &mut D,
connectors: api::SessionConnectorDatas,
+ fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,
+ mut backend_input: dsl_inputs::BackendInput,
+ transaction_type: enums::TransactionType,
) -> RouterResult<api::SessionConnectorDatas>
where
F: Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F>,
{
let chosen = connectors.apply_filter_for_session_routing();
- let sfr = SessionFlowRoutingInput {
+
+ let active_mca_ids =
+ routing::get_active_mca_ids(&state, platform.get_processor().get_key_store())
+ .await
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Active mca_ids not found".to_string(),
+ })?;
+
+ let session_input = routing::SessionRoutingInput {
state: &state,
- country: payment_data
- .get_address()
- .get_payment_method_billing()
- .and_then(|address| address.address.as_ref())
- .and_then(|details| details.country),
+ business_profile,
key_store: platform.get_processor().get_key_store(),
merchant_account: platform.get_processor().get_account(),
- payment_attempt: payment_data.get_payment_attempt(),
- payment_intent: payment_data.get_payment_intent(),
- chosen,
+ transaction_type: &transaction_type,
+ chosen: &chosen,
+ active_mca_ids: &active_mca_ids,
+ default_config: &fallback_config,
+ backend_input: &mut backend_input,
};
- let (result, routing_approach) = self_routing::perform_session_flow_routing(
- sfr,
- business_profile,
- &enums::TransactionType::Payment,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error performing session flow routing")?;
- payment_data.set_routing_approach_in_attempt(routing_approach);
+ let routing_algorithm: routing::MerchantAccountRoutingAlgorithm = business_profile
+ .routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("MerchantAccountRoutingAlgorithm"))
+ .transpose()
+ .inspect_err(|err| {
+ logger::error!(
+ error=?err,
+ "Invalid merchant routing algorithm, falling back to default"
+ );
+ })
+ .ok()
+ .flatten()
+ .unwrap_or_default();
- let final_list = connectors.filter_and_validate_for_session_flow(&result)?;
+ let session_routing_stage = routing::SessionRoutingStage {
+ ctx: routing::SessionRoutingContext {
+ routing_algorithm: routing_algorithm.into(),
+ },
+ };
+
+ let outcome = session_routing_stage
+ .route(session_input)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("error performing session routing stage")?;
+
+ payment_data.set_routing_approach_in_attempt(Some(outcome.routing_approach));
+
+ let final_list = connectors.filter_and_validate_for_session_flow(&outcome.session_output)?;
Ok(final_list)
}
@@ -10504,6 +10570,7 @@ pub struct SessionTokenRoutingResult {
pub routing_result:
FxHashMap<common_enums::PaymentMethodType, Vec<api::routing::SessionRoutingChoice>>,
}
+
#[cfg(feature = "v2")]
pub async fn perform_session_token_routing<F, D>(
state: SessionState,
@@ -10517,7 +10584,7 @@ where
D: OperationSessionGetters<F>,
{
let chosen = connectors.apply_filter_for_session_routing();
- let sfr = SessionFlowRoutingInput {
+ let sfr = routing::SessionFlowRoutingInput {
country: payment_data
.get_payment_intent()
.billing_address
@@ -10528,7 +10595,7 @@ where
chosen,
};
- let result = self_routing::perform_session_flow_routing(
+ let result = routing::perform_session_flow_routing(
&state,
platform.get_processor().get_key_store(),
sfr,
@@ -10603,117 +10670,29 @@ pub async fn route_connector_v2_for_payments(
#[allow(clippy::too_many_arguments)]
pub async fn static_dynamic_routing_v1_for_payments(
state: &SessionState,
- platform: &domain::Platform,
business_profile: &domain::Profile,
- transaction_data: core_routing::PaymentsDslInput<'_>,
- eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
+ payment_dsl_input: core_routing::PaymentsDslInput<'_>,
+ backend_input: euclid::backend::BackendInput,
fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,
) -> RouterResult<routing::RoutingConnectorOutcomeWithApproachAndEligibility> {
- let txn_type = transaction_type_from_payments_dsl(&transaction_data);
- 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()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Could not decode merchant routing algorithm ref")?
- .unwrap_or_default();
-
- algorithm_ref.algorithm_id
- };
-
- let cached_algorithm = routing_algorithm_id
- .async_and_then(|routing_algorithm_id| async move {
- routing::try_ensure_algorithm_cached_v1(
- state,
- &business_profile.merchant_id,
- &routing_algorithm_id,
- business_profile.get_id(),
- &txn_type,
- )
- .await
- })
- .await;
-
- let static_input = routing::StaticRoutingInput {
- platform,
+ let (static_connectors, static_approach) = routing::perform_static_routing_with_de(
+ state,
business_profile,
- eligible_connectors: eligible_connectors.as_ref(),
- transaction_data: &transaction_data,
- };
-
- let static_stage = cached_algorithm.map(|cached_algorithm| routing::StaticRoutingStage {
- ctx: routing::RoutingContext {
- routing_algorithm: cached_algorithm,
- },
- });
-
- let (static_connectors, static_approach) = static_stage
- .clone()
- .async_and_then(|static_stage| async move {
- static_stage
- .route(static_input)
- .await
- .inspect_err(|err| {
- logger::error!(
- error=?err,
- "euclid: static routing failed"
- );
- })
- .ok()
- .map(|outcome| routing::RoutingConnectorOutcome {
- connectors: outcome.connectors,
- })
- })
- .await
- .unwrap_or_else(routing::RoutingConnectorOutcome::empty)
- .resolve_or_fallback_with_approach(
- "static-routing",
- &fallback_config,
- static_stage
- .as_ref()
- .map(|s| s.routing_approach())
- .unwrap_or(common_enums::RoutingApproach::DefaultFallback),
- common_enums::RoutingApproach::DefaultFallback,
- );
+ &payment_dsl_input,
+ &backend_input,
+ &fallback_config,
+ )
+ .await?;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
- let (connectors, routing_approach) = {
- let static_connectors_ref = &static_connectors;
- let transaction_data_ref = &transaction_data;
-
- business_profile
- .dynamic_routing_algorithm
- .as_ref()
- .map(|_| routing::DynamicRoutingStage)
- .async_and_then(|dynamic_routing_stage| async move {
- let dynamic_routing_input = routing::DynamicRoutingInput {
- state,
- business_profile,
- transaction_data: transaction_data_ref,
- static_connectors: static_connectors_ref,
- };
-
- dynamic_routing_stage
- .route(dynamic_routing_input)
- .await
- .inspect_err(|err| {
- logger::error!(
- error=?err,
- "euclid: dynamic routing failed"
- );
- })
- .ok()
- .flatten()
- .map(|outcome| routing::RoutingConnectorOutcomeWithApproach {
- connectors: outcome.connectors,
- routing_approach: outcome.routing_approach,
- })
- })
- .await
- .unwrap_or_else(routing::RoutingConnectorOutcomeWithApproach::empty)
- .resolve_or_fallback("dynamic-routing", static_connectors_ref, static_approach)
- };
+ let (connectors, routing_approach) = routing::perform_dynamic_routing_if_enabled(
+ state,
+ business_profile,
+ &payment_dsl_input,
+ &static_connectors,
+ static_approach,
+ )
+ .await;
#[cfg(not(all(feature = "v1", feature = "dynamic_routing")))]
let (connectors, routing_approach) = (static_connectors, static_approach);
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 591ebef393..f8fe81c915 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -16,7 +16,6 @@ use api_models::{
routing::ConnectorSelection,
};
use common_types::payments as common_payments_types;
-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use common_utils::ext_traits::AsyncExt;
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
@@ -109,7 +108,6 @@ pub struct SessionFlowRoutingInput<'a> {
pub struct SessionRoutingPmTypeInput<'a> {
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
- attempt_id: &'a str,
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
@@ -129,7 +127,7 @@ type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
-enum MerchantAccountRoutingAlgorithm {
+pub enum MerchantAccountRoutingAlgorithm {
V1(routing_types::RoutingAlgorithmRef),
}
@@ -672,6 +670,12 @@ pub trait RoutingStage: Send + Sync {
fn routing_approach(&self) -> common_enums::RoutingApproach;
}
+#[cfg(feature = "v1")]
+#[derive(Clone)]
+pub struct SessionRoutingContext {
+ pub routing_algorithm: Arc<MerchantAccountRoutingAlgorithm>,
+}
+
#[derive(Clone)]
pub struct RoutingContext {
pub routing_algorithm: Arc<CachedAlgorithm>,
@@ -754,10 +758,7 @@ impl RoutingStage for StraightThroughRoutingStage {
#[derive(Clone)]
pub struct StaticRoutingInput<'a> {
- pub platform: &'a domain::Platform,
- pub business_profile: &'a domain::Profile,
- pub eligible_connectors: Option<&'a Vec<api_enums::RoutableConnectors>>,
- pub transaction_data: &'a routing::PaymentsDslInput<'a>,
+ pub backend_input: &'a backend::BackendInput,
}
#[derive(Clone)]
@@ -772,13 +773,11 @@ impl RoutingStage for StaticRoutingStage {
fn route<'a>(&'a self, input: Self::Input<'a>) -> Self::Fut<'a> {
Box::pin(async move {
- let connectors = static_routing_v1(
- &self.ctx.routing_algorithm,
- &routing::TransactionData::Payment(input.transaction_data.clone()),
- )
- .await
- .change_context(errors::RoutingError::DslExecutionError)
- .attach_printable("euclid: unable to perform static routing")?;
+ let connectors =
+ static_routing_v1(&self.ctx.routing_algorithm, input.backend_input.clone())
+ .await
+ .change_context(errors::RoutingError::DslExecutionError)
+ .attach_printable("euclid: unable to perform static routing")?;
Ok(RoutingConnectorOutcome { connectors })
})
@@ -789,6 +788,356 @@ impl RoutingStage for StaticRoutingStage {
}
}
+pub struct DecisionEngineStaticRoutingInput<'a> {
+ pub state: &'a SessionState,
+ pub business_profile: &'a domain::Profile,
+ pub backend_input: backend::BackendInput,
+ pub fallback_config: &'a [routing_types::RoutableConnectorChoice],
+ pub payment_id: String,
+}
+
+pub struct DecisionEngineStaticRoutingStage;
+
+impl RoutingStage for DecisionEngineStaticRoutingStage {
+ type Input<'a> = DecisionEngineStaticRoutingInput<'a>;
+ type Output = RoutingConnectorOutcome;
+ 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 = if !input.state.conf.open_router.static_routing_enabled {
+ logger::debug!("decision engine not enabled");
+ Vec::default()
+ } else {
+ utils::decision_engine_routing(
+ input.state,
+ input.backend_input.clone(),
+ input.business_profile,
+ input.payment_id,
+ input.fallback_config.to_vec(),
+ )
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ error=?err,
+ "decision engine evaluation failed"
+ );
+ })
+ .unwrap_or_default()
+ };
+ Ok(RoutingConnectorOutcome { connectors })
+ })
+ }
+
+ fn routing_approach(&self) -> common_enums::RoutingApproach {
+ common_enums::RoutingApproach::Other("DecisionEngineStaticRouting".to_string())
+ }
+}
+
+#[cfg(feature = "v1")]
+pub async fn perform_static_routing_with_de(
+ state: &SessionState,
+ business_profile: &domain::Profile,
+ payment_dsl_input: &routing::PaymentsDslInput<'_>,
+ backend_input: &backend::BackendInput,
+ fallback_config: &[api_models::routing::RoutableConnectorChoice],
+) -> errors::RouterResult<(
+ Vec<routing_types::RoutableConnectorChoice>,
+ common_enums::RoutingApproach,
+)> {
+ let txn_type = routing::transaction_type_from_payments_dsl(payment_dsl_input);
+
+ let routing_algorithm_id = business_profile
+ .routing_algorithm
+ .clone()
+ .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .unwrap_or_default()
+ .algorithm_id;
+
+ let cached_algorithm = routing_algorithm_id
+ .async_and_then(|routing_algorithm_id| async move {
+ try_ensure_algorithm_cached_v1(
+ state,
+ &business_profile.merchant_id,
+ &routing_algorithm_id,
+ business_profile.get_id(),
+ &txn_type,
+ )
+ .await
+ })
+ .await;
+
+ let static_input = StaticRoutingInput { backend_input };
+
+ let static_stage = cached_algorithm.map(|algo| StaticRoutingStage {
+ ctx: RoutingContext {
+ routing_algorithm: algo,
+ },
+ });
+
+ let (static_connectors, static_approach) = static_stage
+ .clone()
+ .async_and_then(|static_stage| async move {
+ static_stage
+ .route(static_input)
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ error=?err,
+ "euclid: static routing failed"
+ );
+ })
+ .ok()
+ .map(|outcome| RoutingConnectorOutcome {
+ connectors: outcome.connectors,
+ })
+ })
+ .await
+ .unwrap_or_else(RoutingConnectorOutcome::empty)
+ .resolve_or_fallback_with_approach(
+ "static-routing",
+ fallback_config,
+ static_stage
+ .as_ref()
+ .map(|s| s.routing_approach())
+ .unwrap_or(common_enums::RoutingApproach::DefaultFallback),
+ common_enums::RoutingApproach::DefaultFallback,
+ );
+
+ let de_stage = DecisionEngineStaticRoutingStage;
+
+ let de_input = DecisionEngineStaticRoutingInput {
+ state,
+ business_profile,
+ backend_input: backend_input.clone(),
+ fallback_config,
+ payment_id: payment_dsl_input
+ .payment_intent
+ .payment_id
+ .get_string_repr()
+ .to_string(),
+ };
+
+ let de_connectors = de_stage
+ .route(de_input)
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ error=?err,
+ "euclid: static routing failed"
+ );
+ })
+ .unwrap_or_else(|_| RoutingConnectorOutcome::empty())
+ .connectors;
+
+ utils::compare_and_log_result(
+ de_connectors.clone(),
+ static_connectors.clone(),
+ "evaluate_routing".to_string(),
+ );
+
+ let final_static_connector =
+ utils::select_routing_result(state, business_profile, static_connectors, de_connectors)
+ .await;
+
+ Ok((final_static_connector, static_approach))
+}
+
+pub struct SessionRoutingInput<'a> {
+ pub state: &'a SessionState,
+ pub business_profile: &'a domain::Profile,
+ pub key_store: &'a domain::MerchantKeyStore,
+ pub merchant_account: &'a domain::MerchantAccount,
+ pub transaction_type: &'a api_enums::TransactionType,
+ pub chosen: &'a api::SessionConnectorDatas,
+ pub active_mca_ids:
+ &'a std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,
+ pub default_config: &'a Vec<routing_types::RoutableConnectorChoice>,
+ pub backend_input: &'a mut backend::BackendInput,
+}
+
+#[cfg(feature = "v1")]
+#[derive(Clone)]
+pub struct SessionRoutingStage {
+ pub ctx: SessionRoutingContext,
+}
+
+#[cfg(feature = "v1")]
+impl RoutingStage for SessionRoutingStage {
+ type Input<'a> = SessionRoutingInput<'a>;
+ type Output = RoutingConnectorOutcomeForSessionRouting;
+ 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 mut pm_type_map: FxHashMap<
+ api_enums::PaymentMethodType,
+ FxHashMap<String, api::GetToken>,
+ > = FxHashMap::default();
+
+ let profile_id = input.business_profile.get_id();
+
+ for connector_data in input.chosen.iter() {
+ pm_type_map
+ .entry(connector_data.payment_method_sub_type)
+ .or_default()
+ .insert(
+ connector_data.connector.connector_name.to_string(),
+ connector_data.connector.get_token.clone(),
+ );
+ }
+
+ let mut final_routing_approach = common_enums::RoutingApproach::DefaultFallback;
+
+ let mut result: FxHashMap<
+ api_enums::PaymentMethodType,
+ Vec<routing_types::SessionRoutingChoice>,
+ > = FxHashMap::default();
+
+ for (pm_type, allowed_connectors) in pm_type_map {
+ let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
+ let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
+
+ input.backend_input.payment_method.payment_method = Some(euclid_pm);
+ input.backend_input.payment_method.payment_method_type = Some(euclid_pmt);
+
+ let algorithm_id = match &*self.ctx.routing_algorithm {
+ MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => {
+ &algorithm_ref.algorithm_id
+ }
+ };
+
+ let cached_algorithm = algorithm_id
+ .clone()
+ .async_and_then(|algorithm_id| async move {
+ try_ensure_algorithm_cached_v1(
+ input.state,
+ &input.business_profile.merchant_id,
+ &algorithm_id,
+ input.business_profile.get_id(),
+ input.transaction_type,
+ )
+ .await
+ })
+ .await;
+
+ let static_input = StaticRoutingInput {
+ backend_input: input.backend_input,
+ };
+
+ let static_stage = cached_algorithm.map(|cached_algorithm| StaticRoutingStage {
+ ctx: RoutingContext {
+ routing_algorithm: cached_algorithm,
+ },
+ });
+
+ let (chosen_connectors, static_approach) = static_stage
+ .clone()
+ .async_and_then(|static_stage| async move {
+ static_stage
+ .route(static_input)
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ error=?err,
+ "euclid: session routing failed"
+ );
+ })
+ .ok()
+ .map(|outcome| RoutingConnectorOutcome {
+ connectors: outcome.connectors,
+ })
+ })
+ .await
+ .unwrap_or_else(RoutingConnectorOutcome::empty)
+ .resolve_or_fallback_with_approach(
+ "static-routing",
+ input.default_config,
+ static_stage
+ .as_ref()
+ .map(|s| s.routing_approach())
+ .unwrap_or(common_enums::RoutingApproach::DefaultFallback),
+ common_enums::RoutingApproach::DefaultFallback,
+ );
+
+ let primary = perform_cgraph_filtering(
+ input.state,
+ input.key_store,
+ chosen_connectors,
+ input.backend_input.clone(),
+ None,
+ profile_id,
+ input.transaction_type,
+ input.active_mca_ids,
+ )
+ .await?;
+
+ let final_selection = if primary.is_empty() {
+ perform_cgraph_filtering(
+ input.state,
+ input.key_store,
+ input.default_config.clone(),
+ input.backend_input.clone(),
+ None,
+ profile_id,
+ input.transaction_type,
+ input.active_mca_ids,
+ )
+ .await?
+ } else {
+ primary
+ };
+
+ let routable_connector_choice_option = if final_selection.is_empty() {
+ (None, static_approach.clone())
+ } else {
+ (Some(final_selection), static_approach)
+ };
+
+ final_routing_approach = routable_connector_choice_option.1;
+
+ if let Some(routable_connector_choice) = routable_connector_choice_option.0 {
+ let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> =
+ Vec::new();
+
+ for selection in routable_connector_choice {
+ let connector_name = selection.connector.to_string();
+ if let Some(get_token) = allowed_connectors.get(&connector_name) {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ &input.state.clone().conf.connectors,
+ &connector_name,
+ get_token.clone(),
+ selection.merchant_connector_id,
+ )
+ .change_context(
+ errors::RoutingError::InvalidConnectorName(connector_name),
+ )?;
+
+ session_routing_choice.push(routing_types::SessionRoutingChoice {
+ connector: connector_data,
+ payment_method_type: pm_type,
+ });
+ }
+ }
+ if !session_routing_choice.is_empty() {
+ result.insert(pm_type, session_routing_choice);
+ }
+ }
+ }
+ Ok(RoutingConnectorOutcomeForSessionRouting {
+ session_output: result,
+ routing_approach: final_routing_approach,
+ })
+ })
+ }
+
+ fn routing_approach(&self) -> common_enums::RoutingApproach {
+ common_enums::RoutingApproach::Other("SessionFlowRouting".to_string())
+ }
+}
+
pub struct RoutingConnectorOutcomeWithApproachAndEligibility {
pub connectors: Vec<routing_types::RoutableConnectorChoice>,
pub routing_approach: common_enums::RoutingApproach,
@@ -1030,9 +1379,11 @@ where
Ok(connector_call_type)
}
-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-pub struct DynamicRoutingStage;
-
+pub struct RoutingConnectorOutcomeForSessionRouting {
+ pub session_output:
+ FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>,
+ pub routing_approach: common_enums::RoutingApproach,
+}
pub struct RoutingConnectorOutcomeWithApproach {
pub connectors: Vec<routing_types::RoutableConnectorChoice>,
pub routing_approach: common_enums::RoutingApproach,
@@ -1066,6 +1417,9 @@ impl RoutingConnectorOutcomeWithApproach {
}
}
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub struct DynamicRoutingStage;
+
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl DynamicRoutingStage {
async fn resolve_dynamic_connectors(
@@ -1154,17 +1508,55 @@ impl RoutingStage for DynamicRoutingStage {
}
}
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn perform_dynamic_routing_if_enabled(
+ state: &SessionState,
+ business_profile: &domain::Profile,
+ payment_dsl_input: &routing::PaymentsDslInput<'_>,
+ static_connectors: &[routing_types::RoutableConnectorChoice],
+ static_approach: common_enums::RoutingApproach,
+) -> (
+ Vec<routing_types::RoutableConnectorChoice>,
+ common_enums::RoutingApproach,
+) {
+ business_profile
+ .dynamic_routing_algorithm
+ .as_ref()
+ .map(|_| DynamicRoutingStage)
+ .async_and_then(|stage| async move {
+ let input = DynamicRoutingInput {
+ state,
+ business_profile,
+ transaction_data: payment_dsl_input,
+ static_connectors,
+ };
+
+ stage
+ .route(input)
+ .await
+ .inspect_err(|err| {
+ logger::error!(
+ error=?err,
+ "euclid: dynamic routing failed"
+ );
+ })
+ .ok()
+ .flatten()
+ .map(|outcome| RoutingConnectorOutcomeWithApproach {
+ connectors: outcome.connectors,
+ routing_approach: outcome.routing_approach,
+ })
+ })
+ .await
+ .unwrap_or_else(RoutingConnectorOutcomeWithApproach::empty)
+ .resolve_or_fallback("dynamic-routing", static_connectors, static_approach)
+}
+
pub async fn static_routing_v1(
routing_algorithm: &CachedAlgorithm,
- transaction_data: &routing::TransactionData<'_>,
+ backend_input: backend::BackendInput,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
logger::debug!("euclid_routing: performing routing for connector selection");
- let backend_input = match transaction_data {
- routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
- #[cfg(feature = "payouts")]
- routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
- };
-
let routable_connectors = match routing_algorithm {
CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
CachedAlgorithm::Priority(plist) => plist.clone(),
@@ -2127,7 +2519,7 @@ pub async fn perform_session_flow_routing(
let session_pm_input = SessionRoutingPmTypeInput {
state: session_input.state,
key_store: session_input.key_store,
- attempt_id: session_input.payment_attempt.get_id(),
+ // attempt_id: session_input.payment_attempt.get_id(),
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index af45d20a0b..de94fc443c 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -2753,3 +2753,29 @@ pub fn log_connectors(stage: &str, connectors: &[routing::RoutableConnectorChoic
names.join(", ")
);
}
+
+pub fn convert_fallback_to_connector_routing_data(
+ state: &SessionState,
+ fallback: &[routing_types::RoutableConnectorChoice],
+) -> RouterResult<Vec<api::ConnectorRoutingData>> {
+ fallback
+ .iter()
+ .map(|choice| {
+ let connector_name = choice.connector.to_string();
+
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &connector_name,
+ api::GetToken::Connector,
+ choice.merchant_connector_id.clone(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ Ok(api::ConnectorRoutingData {
+ connector_data,
+ network: None,
+ action_type: None,
+ })
+ })
+ .collect()
+}