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
feat(routing): move dynamic routing decisions to the Decision Engine (#14204)
Ankit Kumar Guptae2ce5780f738
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 73a942908f..3e6339a3ec 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -30179,12 +30179,6 @@}],"nullable": true- },- "eliminationEnabled": {- "type": "boolean",- "description": "Whether elimination logic is enabled for filtering gateways",- "example": true,- "nullable": true}}},diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rsindex 43122d6c25..222398cf23 100644--- a/crates/api_models/src/open_router.rs+++ b/crates/api_models/src/open_router.rs@@ -35,10 +35,6 @@ pub struct OpenRouterDecideGatewayRequest {/// Algorithm to use for ranking and selecting gateways#[schema(value_type = Option<RankingAlgorithm>, example = "SR_BASED_ROUTING")]pub ranking_algorithm: Option<RankingAlgorithm>,-- /// Whether elimination logic is enabled for filtering gateways- #[schema(value_type = Option<bool>, example = true)]- pub elimination_enabled: Option<bool>,}#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex f3c644c5d6..3859c55dbb 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -43,6 +43,8 @@ use crate::core::offer_engine;#[cfg(feature = "v1")]use crate::core::payment_methods::transformers::call_modular_payment_method_update;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]+use crate::core::payments::routing::utils as routing_utils;+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]use crate::core::routing::helpers as routing_helpers;#[cfg(feature = "v2")]use crate::utils::OptionExt;@@ -615,6 +617,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorroutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1195,6 +1199,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> forroutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await}@@ -1355,6 +1361,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSessionData>routable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1669,6 +1677,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData>routable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1711,6 +1721,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPreAuthorizeCroutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1747,6 +1759,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> froutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1789,6 +1803,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCaproutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1831,6 +1847,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCaproutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1873,6 +1891,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsExtendAuthoriroutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1911,6 +1931,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsApproveData>routable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1947,6 +1969,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRejectData> froutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -1993,6 +2017,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDaroutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await?;@@ -2213,6 +2239,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeDataroutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await}@@ -2353,6 +2381,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(RoutableConnectorChoice,>,#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ dimensions: &DimensionsWithProcessorAndProviderMerchantId,) -> RouterResult<PaymentData<F>> {let key_manager_state = &state.into();// Update additional payment data with the payment method response that we received from connector@@ -3210,40 +3240,21 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(#[cfg(all(feature = "v1", feature = "dynamic_routing"))]{- if payment_intent.status.is_in_terminal_state()- && business_profile.dynamic_routing_algorithm.is_some()- {- let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef =- business_profile- .dynamic_routing_algorithm- .clone()- .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("DynamicRoutingAlgorithmRef not found in profile")?;-+ if payment_intent.status.is_in_terminal_state() {let state = state.clone();let profile_id = business_profile.get_id().to_owned();+ let de_dimensions = dimensions.with_profile_id(profile_id.clone());let payment_attempt = payment_attempt.clone();tokio::spawn(async move {- let should_route_to_open_router =- state.conf.open_router.dynamic_routing_enabled;- let is_success_rate_based = matches!(- payment_attempt.routing_approach,- Some(enums::RoutingApproach::SuccessRateExploitation)- | Some(enums::RoutingApproach::SuccessRateExploration)- );-- if should_route_to_open_router && is_success_rate_based {+ if routing_utils::is_decision_engine_routing_effective(&state, &de_dimensions)+ .await+ {routing_helpers::update_gateway_score_helper_with_open_router(&state,&payment_attempt,&profile_id,- dynamic_routing_algo_ref.clone(),).await.map_err(|e| logger::error!(open_router_update_gateway_score_err=?e))@@ -4040,6 +4051,8 @@ implroutable_connector,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]business_profile,+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]+ _dimensions,)).await}diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 6bf508dc13..3d180c31d2 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -1683,86 +1683,27 @@ impl HybridRoutingStage {fn build_dynamic_routing_request(&self,input: &HybridRoutingInput<'_>,- ) -> (Option<OpenRouterDecideGatewayRequest>, Option<u8>) {- if !input.state.conf.open_router.dynamic_routing_enabled {- (None, None)- } else if let Some(dynamic_routing_algo) =- input.business_profile.dynamic_routing_algorithm.clone()- {- match dynamic_routing_algo.parse_value::<api_routing::DynamicRoutingAlgorithmRef>(- "DynamicRoutingAlgorithmRef",- ) {- Ok(dynamic_routing_config) => {- let dynamic_routing_volume_split = dynamic_routing_config- .dynamic_routing_volume_split- .unwrap_or_default();- let is_dynamic_feature_enabled = dynamic_routing_config- .is_success_rate_routing_enabled()- || dynamic_routing_config.is_elimination_enabled();-- if !is_dynamic_feature_enabled {- logger::debug!(- "euclid: dynamic routing config present but dynamic features are disabled"- );- (None, Some(dynamic_routing_volume_split))- } else {- match perform_dynamic_routing_volume_split(- vec![- api_models::routing::RoutingVolumeSplit {- routing_type: api_models::routing::RoutingType::Dynamic,- split: dynamic_routing_volume_split,- },- api_models::routing::RoutingVolumeSplit {- routing_type: api_models::routing::RoutingType::Static,- split: crate::consts::DYNAMIC_ROUTING_MAX_VOLUME- - dynamic_routing_volume_split,- },- ],- None,- ) {- Ok(routing_choice)- if routing_choice.routing_type.is_dynamic_routing() =>- {- (- Some(OpenRouterDecideGatewayRequest::construct_sr_request(- input.payment_dsl_input.payment_attempt,- input.static_connectors.to_vec(),- Some(or_types::RankingAlgorithm::SrBasedRouting),- dynamic_routing_config.is_elimination_enabled(),- )),- Some(dynamic_routing_volume_split),- )- }- Ok(_) => (None, Some(dynamic_routing_volume_split)),- Err(error) => {- logger::error!(- error=?error,- "euclid: failed to perform dynamic routing volume split for hybrid routing"- );- (None, Some(dynamic_routing_volume_split))- }- }- }- }- Err(error) => {- logger::error!(- error=?error,- "euclid: failed to parse dynamic routing config for hybrid routing"- );- (None, None)- }- }- } else {- (None, None)- }+ ) -> Option<OpenRouterDecideGatewayRequest> {+ input+ .state+ .conf+ .open_router+ .dynamic_routing_enabled+ .then(|| {+ OpenRouterDecideGatewayRequest::construct_sr_request(+ input.payment_dsl_input.payment_attempt,+ input.static_connectors.to_vec(),+ Some(or_types::RankingAlgorithm::SrBasedRouting),+ )+ })}#[cfg(not(all(feature = "v1", feature = "dynamic_routing")))]fn build_dynamic_routing_request(&self,_input: &HybridRoutingInput<'_>,- ) -> (Option<OpenRouterDecideGatewayRequest>, Option<u8>) {- (None, None)+ ) -> Option<OpenRouterDecideGatewayRequest> {+ None}}@@ -1774,8 +1715,7 @@ impl RoutingStage for HybridRoutingStage {fn route<'a>(&'a self, input: Self::Input<'a>) -> Self::Fut<'a> {Box::pin(async move {- let (dynamic_routing_request, _dynamic_routing_volume_split) =- self.build_dynamic_routing_request(&input);+ let dynamic_routing_request = self.build_dynamic_routing_request(&input);// Under DE cutover, always evaluate the profile's rule on DE; the caller falls back to HS static/default on empty or error.let should_include_static_request = input.state.conf.open_router.static_routing_enabled;@@ -3759,7 +3699,6 @@ pub async fn perform_dynamic_routing_with_open_router(routable_connectors.clone(),profile.get_id(),&payment_data,- is_elimination_enabled,).await?;@@ -3993,7 +3932,6 @@ pub async fn perform_decide_gateway_call_with_open_router(mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>,profile_id: &common_utils::id_type::ProfileId,payment_attempt: &oss_storage::PaymentAttempt,- is_elimination_enabled: bool,) -> RoutingResult<RoutingConnectorOutcomeWithApproach> {logger::debug!("performing decide_gateway call with open_router for profile {}",@@ -4004,7 +3942,6 @@ pub async fn perform_decide_gateway_call_with_open_router(payment_attempt,routable_connectors.clone(),Some(or_types::RankingAlgorithm::SrBasedRouting),- is_elimination_enabled,);let routing_events_wrapper = utils::RoutingEventsWrapper::new(diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rsindex 4a2d0fc7d7..c4582bb776 100644--- a/crates/router/src/core/payments/routing/utils.rs+++ b/crates/router/src/core/payments/routing/utils.rs@@ -2673,13 +2673,13 @@ pub async fn get_routing_result_source(}}-/// Effective cutover: routing_result_source is DecisionEngine AND the global-/// static_routing_enabled flag is on — the flag always wins, for APIs and payment paths alike.+/// Effective cutover routing_result_source is DecisionEngine and either global routing flag (static or dynamic) is on - the flags always win, for APIs and payment paths alike.pub async fn is_decision_engine_routing_effective(state: &SessionState,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,) -> bool {- state.conf.open_router.static_routing_enabled+ (state.conf.open_router.static_routing_enabled+ || state.conf.open_router.dynamic_routing_enabled)&& matches!(get_routing_result_source(state, dimensions).await,api_routing::RoutingResultSource::DecisionEngine@@ -2695,7 +2695,7 @@ pub async fn select_routing_result<T>(whereT: Clone + IntoIterator,{- // Same predicate as every other consumer: with the global flag off the profile is+ // Same predicate as every other consumer: with both global flags off the profile is// Hyperswitch-routed, so reads must not serve DE records the payment path ignores.let routing_result_source = if is_decision_engine_routing_effective(state, dimensions).await {api_routing::RoutingResultSource::DecisionEnginediff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rsindex ba95825f6c..decebde208 100644--- a/crates/router/src/core/routing/helpers.rs+++ b/crates/router/src/core/routing/helpers.rs@@ -843,44 +843,37 @@ pub async fn update_gateway_score_helper_with_open_router(state: &SessionState,payment_attempt: &storage::PaymentAttempt,profile_id: &id_type::ProfileId,- dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,) -> RouterResult<()> {- let is_success_rate_routing_enabled =- dynamic_routing_algo_ref.is_success_rate_routing_enabled();- let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled();-- if is_success_rate_routing_enabled || is_elimination_enabled {- let payment_connector = &payment_attempt.connector.clone().ok_or(- errors::ApiErrorResponse::GenericNotFoundError {- message: "unable to derive payment connector from payment attempt".to_string(),- },- )?;+ let payment_connector = payment_attempt.connector.clone().ok_or(+ errors::ApiErrorResponse::GenericNotFoundError {+ message: "unable to derive payment connector from payment attempt".to_string(),+ },+ )?;- let routable_connector = routing_types::RoutableConnectorChoice {- choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,- connector: euclid::enums::RoutableConnectors::from_str(payment_connector.as_str())- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("unable to infer routable_connector from connector")?,- merchant_connector_id: payment_attempt.merchant_connector_id.clone(),- };+ let routable_connector = routing_types::RoutableConnectorChoice {+ choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,+ connector: euclid::enums::RoutableConnectors::from_str(payment_connector.as_str())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("unable to infer routable_connector from connector")?,+ merchant_connector_id: payment_attempt.merchant_connector_id.clone(),+ };- logger::debug!(- "performing update-gateway-score for gateway with id {} in open_router for profile: {}",- routable_connector,- profile_id.get_string_repr()- );- routing::payments_routing::update_gateway_score_with_open_router(- state,- routable_connector.clone(),- profile_id,- &payment_attempt.merchant_id,- &payment_attempt.payment_id,- payment_attempt.status,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to update gateway score in open_router service")?;- }+ logger::debug!(+ "decision_engine: performing update-gateway-score for gateway with id {} in open_router for profile: {}",+ routable_connector,+ profile_id.get_string_repr()+ );+ routing::payments_routing::update_gateway_score_with_open_router(+ state,+ routable_connector,+ profile_id,+ &payment_attempt.merchant_id,+ &payment_attempt.payment_id,+ payment_attempt.status,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to update gateway score in open_router service")?;Ok(())}diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rsindex 5f244f4bd4..0e3128567d 100644--- a/crates/router/src/core/routing/transformers.rs+++ b/crates/router/src/core/routing/transformers.rs@@ -125,7 +125,6 @@ pub trait OpenRouterDecideGatewayRequestExt {attempt: &PaymentAttempt,eligible_gateway_list: Vec<RoutableConnectorChoice>,ranking_algorithm: Option<RankingAlgorithm>,- is_elimination_enabled: bool,) -> SelfwhereSelf: Sized;@@ -146,7 +145,6 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {attempt: &PaymentAttempt,eligible_gateway_list: Vec<RoutableConnectorChoice>,ranking_algorithm: Option<RankingAlgorithm>,- is_elimination_enabled: bool,) -> Self {Self {payment_info: PaymentInfo {@@ -167,7 +165,6 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {.collect(),),ranking_algorithm,- elimination_enabled: Some(is_elimination_enabled),}}@@ -192,7 +189,6 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {// eligible gateway list is not used in debit routingeligible_gateway_list: None,ranking_algorithm,- elimination_enabled: None,}}}