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
refactor(routing): de-couple dynamic and static routing (#10854)
Prajjwal Kumar4d69890b6524
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 7dacc66992..39a52ab41f 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -75,6 +75,7 @@ use redis_interface::errors::RedisError;use router_env::{instrument, tracing};#[cfg(feature = "olap")]use router_types::transformers::ForeignFrom;+use routing::RoutingStage;use rustc_hash::FxHashMap;use scheduler::utils as pt_utils;#[cfg(feature = "v2")]@@ -99,7 +100,7 @@ use self::{use super::{errors::StorageErrorExt,payment_methods::surcharge_decision_configs,- routing::TransactionData,+ routing::{transaction_type_from_payments_dsl, TransactionData},unified_connector_service::{extract_gateway_system_from_payment_intent, should_call_unified_connector_service,},@@ -10553,6 +10554,17 @@ whereF: Send + Clone,D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,{+ 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();@@ -10562,83 +10574,127 @@ where.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Could not decode merchant routing algorithm ref")?.unwrap_or_default();+algorithm_ref.algorithm_id};- let (connectors, routing_approach) = routing::perform_static_routing_v1(- state,- platform.get_processor().get_account().get_id(),- routing_algorithm_id.as_ref(),+ 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,business_profile,- &TransactionData::Payment(transaction_data.clone()),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ eligible_connectors: eligible_connectors.as_ref(),+ transaction_data: &transaction_data,+ };- payment_data.set_routing_approach_in_attempt(routing_approach);+ 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,+ );#[cfg(all(feature = "v1", feature = "dynamic_routing"))]- let payment_attempt = transaction_data.payment_attempt.clone();+ let (connectors, routing_approach) = {+ let static_connectors_ref = &static_connectors;+ let transaction_data_ref = &transaction_data;- let connectors = routing::perform_eligibility_analysis_with_fallback(- &state.clone(),+ 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)+ };++ #[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(),connectors,- &TransactionData::Payment(transaction_data),+ &TransactionData::Payment(transaction_data.clone()),eligible_connectors,business_profile,).await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed eligibility analysis and fallback")?;-- // dynamic success based connector selection- #[cfg(all(feature = "v1", feature = "dynamic_routing"))]- let connectors = if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() {- let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo- .parse_value("DynamicRoutingAlgorithmRef")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?;- let dynamic_split = api_models::routing::RoutingVolumeSplit {- routing_type: api_models::routing::RoutingType::Dynamic,- split: dynamic_routing_config- .dynamic_routing_volume_split- .unwrap_or_default(),- };- let static_split: api_models::routing::RoutingVolumeSplit =- api_models::routing::RoutingVolumeSplit {- routing_type: api_models::routing::RoutingType::Static,- split: consts::DYNAMIC_ROUTING_MAX_VOLUME- - dynamic_routing_config- .dynamic_routing_volume_split- .unwrap_or_default(),- };- let volume_split_vec = vec![dynamic_split, static_split];- let routing_choice = routing::perform_dynamic_routing_volume_split(volume_split_vec, None)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to perform volume split on routing type")?;+ .unwrap_or_else(|err| {+ logger::error!(+ error=?err,+ "euclid: eligibility analysis failed, using fallback connectors"+ );+ fallback_config.clone()+ });- if routing_choice.routing_type.is_dynamic_routing()- && state.conf.open_router.dynamic_routing_enabled- {- routing::perform_dynamic_routing_with_open_router(- state,- connectors.clone(),- business_profile,- payment_attempt,- payment_data,- )- .await- .map_err(|e| logger::error!(open_routing_error=?e))- .unwrap_or(connectors)- } else {- connectors- }- } else {- connectors- };+ core_routing::log_connectors("eligibility", &routable_connectors);- let connector_data = 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(@@ -10651,7 +10707,7 @@ where}).collect::<CustomResult<Vec<_>, _>>().change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Invalid connector name received")?;+ .attach_printable("euclid: Invalid connector name received")?;decide_multiplex_connector_for_normal_or_recurring_payment(state,diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 4d781c8221..a62576d936 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -4,7 +4,7 @@ pub mod utils;use std::collections::hash_map;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]use std::hash::{Hash, Hasher};-use std::{collections::HashMap, str::FromStr, sync::Arc};+use std::{collections::HashMap, future::Future, pin::Pin, str::FromStr, sync::Arc};#[cfg(feature = "v1")]use api_models::open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest};@@ -653,6 +653,210 @@ pub fn make_dsl_input(})}+type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;+pub trait RoutingStage: Send + Sync {+ type Input<'a>+ where+ Self: 'a;++ type Output;+ type Fut<'a>: Future<Output = RoutingResult<Self::Output>> + Send+ where+ Self: 'a;++ fn route<'a>(&'a self, input: Self::Input<'a>) -> Self::Fut<'a>;++ fn routing_approach(&self) -> common_enums::RoutingApproach;+}++#[derive(Clone)]+pub struct RoutingContext {+ pub routing_algorithm: Arc<CachedAlgorithm>,+}++pub struct RoutingConnectorOutcome {+ pub connectors: Vec<routing_types::RoutableConnectorChoice>,+}++impl RoutingConnectorOutcome {+ pub fn resolve_or_fallback_with_approach(+ self,+ stage: &'static str,+ fallback: &[routing_types::RoutableConnectorChoice],+ success_approach: common_enums::RoutingApproach,+ 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);+ (fallback.to_vec(), fallback_approach)+ } else {+ routing::log_connectors(stage, &self.connectors);+ (self.connectors, success_approach)+ }+ }++ pub fn empty() -> Self {+ Self {+ connectors: Vec::new(),+ }+ }+}++#[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>,+}++#[derive(Clone)]+pub struct StaticRoutingStage {+ pub ctx: RoutingContext,+}++impl RoutingStage for StaticRoutingStage {+ type Input<'a> = StaticRoutingInput<'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 = 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")?;++ Ok(RoutingConnectorOutcome { connectors })+ })+ }++ fn routing_approach(&self) -> common_enums::RoutingApproach {+ common_enums::RoutingApproach::RuleBasedRouting+ }+}++#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+pub struct DynamicRoutingStage;++#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+impl DynamicRoutingStage {+ async fn resolve_dynamic_connectors(+ &self,+ input: &DynamicRoutingInput<'_>,+ routing_type: &api_models::routing::RoutingType,+ ) -> RoutingResult<Option<RoutingConnectorOutcomeWithApproach>> {+ if !routing_type.is_dynamic_routing()+ || !input.state.conf.open_router.dynamic_routing_enabled+ {+ Ok(None)+ } else {+ let payment_attempt = input.transaction_data.payment_attempt.clone();+ match perform_dynamic_routing_with_open_router(+ input.state,+ input.static_connectors.to_vec(),+ input.business_profile,+ payment_attempt,+ )+ .await+ {+ Ok(result) => Ok(result),+ Err(e) => {+ logger::error!(euclid_open_router_error=?e);+ Ok(None)+ }+ }+ }+ }+}++#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+pub struct DynamicRoutingInput<'a> {+ pub state: &'a SessionState,+ pub business_profile: &'a domain::Profile,+ pub transaction_data: &'a routing::PaymentsDslInput<'a>,+ pub static_connectors: &'a [routing_types::RoutableConnectorChoice],+}++#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+impl RoutingStage for DynamicRoutingStage {+ type Input<'a> = DynamicRoutingInput<'a>;+ type Output = Option<RoutingConnectorOutcomeWithApproach>;+ 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 Some(algo) = input.business_profile.dynamic_routing_algorithm.clone() else {+ return Ok(None);+ };++ let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo+ .parse_value("DynamicRoutingAlgorithmRef")+ .change_context(errors::RoutingError::DeserializationError {+ from: "json".into(),+ to: "DynamicAlgorithmRef".into(),+ })?;++ let dynamic_split = api_models::routing::RoutingVolumeSplit {+ routing_type: api_models::routing::RoutingType::Dynamic,+ split: dynamic_routing_config+ .dynamic_routing_volume_split+ .unwrap_or_default(),+ };++ let static_split = api_models::routing::RoutingVolumeSplit {+ routing_type: api_models::routing::RoutingType::Static,+ split: crate::consts::DYNAMIC_ROUTING_MAX_VOLUME+ - dynamic_routing_config+ .dynamic_routing_volume_split+ .unwrap_or_default(),+ };++ let routing_choice =+ perform_dynamic_routing_volume_split(vec![dynamic_split, static_split], None)+ .change_context(errors::RoutingError::VolumeSplitFailed)+ .attach_printable("euclid: failed to perform volume split on routing type")?;++ self.resolve_dynamic_connectors(&input, &routing_choice.routing_type)+ .await+ })+ }++ fn routing_approach(&self) -> common_enums::RoutingApproach {+ common_enums::RoutingApproach::Other("DynamicRouting".to_string())+ }+}++pub async fn static_routing_v1(+ routing_algorithm: &CachedAlgorithm,+ transaction_data: &routing::TransactionData<'_>,+) -> 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(),+ CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec())+ .change_context(errors::RoutingError::ConnectorSelectionFailed)?,+ CachedAlgorithm::Advanced(interpreter) => {+ execute_dsl_and_get_connector_v1(backend_input, interpreter)?+ }+ };+ Ok(routable_connectors)+}+pub async fn perform_static_routing_v1(state: &SessionState,merchant_id: &common_utils::id_type::MerchantId,@@ -790,7 +994,7 @@ pub async fn perform_static_routing_v1())}-async fn ensure_algorithm_cached_v1(+pub async fn ensure_algorithm_cached_v1(state: &SessionState,merchant_id: &common_utils::id_type::MerchantId,algorithm_id: &common_utils::id_type::RoutingId,@@ -836,6 +1040,30 @@ async fn ensure_algorithm_cached_v1(Ok(algorithm)}+pub async fn try_ensure_algorithm_cached_v1(+ state: &SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ algorithm_id: &common_utils::id_type::RoutingId,+ profile_id: &common_utils::id_type::ProfileId,+ transaction_type: &api_enums::TransactionType,+) -> Option<Arc<CachedAlgorithm>> {+ ensure_algorithm_cached_v1(+ state,+ merchant_id,+ algorithm_id,+ profile_id,+ transaction_type,+ )+ .await+ .inspect_err(|err| {+ logger::error!(+ error=?err,+ "euclid_routing: ensure_algorithm_cached failed, falling back"+ );+ })+ .ok()+}+pub fn perform_straight_through_routing(algorithm: &routing_types::StraightThroughAlgorithm,creds_identifier: Option<&str>,@@ -1891,18 +2119,45 @@ 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<F, D>(+pub async fn perform_dynamic_routing_with_open_router(state: &SessionState,routable_connectors: Vec<api_routing::RoutableConnectorChoice>,profile: &domain::Profile,payment_data: oss_storage::PaymentAttempt,- old_payment_data: &mut D,-) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>-where- F: Send + Clone,- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,-{+) -> RoutingResult<Option<RoutingConnectorOutcomeWithApproach>> {let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile.dynamic_routing_algorithm.clone()@@ -1934,7 +2189,6 @@ whereprofile.get_id(),&payment_data,is_elimination_enabled,- old_payment_data,).await?;@@ -1942,7 +2196,7 @@ where// This will initiate the elimination process for the connector.// Penalize the elimination score of the connector before making a payment.// Once the payment is made, we will update the score based on the payment status- if let Some(connector) = connectors.first() {+ 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()@@ -1958,11 +2212,10 @@ where.await?}}- connectors+ Some(connectors)} else {- routable_connectors+ None};-Ok(connectors)}@@ -2164,18 +2417,13 @@ where#[cfg(all(feature = "v1", feature = "dynamic_routing"))]#[instrument(skip_all)]-pub async fn perform_decide_gateway_call_with_open_router<F, D>(+pub async fn perform_decide_gateway_call_with_open_router(state: &SessionState,mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>,profile_id: &common_utils::id_type::ProfileId,payment_attempt: &oss_storage::PaymentAttempt,is_elimination_enabled: bool,- old_payment_data: &mut D,-) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>-where- F: Send + Clone,- D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,-{+) -> RoutingResult<RoutingConnectorOutcomeWithApproach> {logger::debug!("performing decide_gateway call with open_router for profile {}",profile_id.get_string_repr()@@ -2232,11 +2480,9 @@ where.to_string(),);- old_payment_data.set_routing_approach_in_attempt(Some(- common_enums::RoutingApproach::from_decision_engine_approach(- &decided_gateway.routing_approach,- ),- ));+ let routing_approach = common_enums::RoutingApproach::from_decision_engine_approach(+ &decided_gateway.routing_approach,+ );if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map {logger::debug!(gateway_priority_map=?gateway_priority_map, routing_approach=decided_gateway.routing_approach, "open_router decide_gateway call response");@@ -2258,7 +2504,10 @@ whererouting_event.set_routable_connectors(routable_connectors.clone());state.event_handler().log_event(&routing_event);- Ok(routable_connectors)+ Ok(RoutingConnectorOutcomeWithApproach {+ connectors: routable_connectors,+ routing_approach,+ })}Err(err) => {logger::error!("open_router_error_response: {:?}", err);@@ -2269,7 +2518,10 @@ where}}?;- Ok(sr_sorted_connectors)+ Ok(RoutingConnectorOutcomeWithApproach {+ connectors: sr_sorted_connectors.connectors,+ routing_approach: sr_sorted_connectors.routing_approach,+ })}#[cfg(all(feature = "v1", feature = "dynamic_routing"))]diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rsindex 7ad8198130..af45d20a0b 100644--- a/crates/router/src/core/routing.rs+++ b/crates/router/src/core/routing.rs@@ -2738,3 +2738,18 @@ pub async fn update_gateway_score_open_router(response,))}++pub fn transaction_type_from_payments_dsl(input: &PaymentsDslInput<'_>) -> enums::TransactionType {+ let txn_data = TransactionData::Payment(input.clone());+ enums::TransactionType::from(&txn_data)+}++pub fn log_connectors(stage: &str, connectors: &[routing::RoutableConnectorChoice]) {+ let names: Vec<String> = connectors.iter().map(|c| c.connector.to_string()).collect();++ router_env::logger::debug!(+ "euclid: connectors after {} = {{{}}}",+ stage,+ names.join(", ")+ );+}