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): add hybrid routing as a routing stage (#11579)

Prajjwal Kumard3de9e4a6538
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 5653550800..e0f8520e94 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -10782,7 +10782,7 @@ pub async fn static_dynamic_routing_v1_for_payments(
backend_input: euclid::backend::BackendInput,
fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,
) -> RouterResult<routing::RoutingConnectorOutcomeWithApproachAndEligibility> {
- let (static_connectors, static_approach) = routing::perform_static_routing_with_de(
+ let (static_connectors, static_approach) = routing::perform_static_routing_locally(
state,
business_profile,
&payment_dsl_input,
@@ -10791,19 +10791,17 @@ pub async fn static_dynamic_routing_v1_for_payments(
)
.await?;
- #[cfg(all(feature = "v1", feature = "dynamic_routing"))]
- let (connectors, routing_approach) = routing::perform_dynamic_routing_if_enabled(
+ let (connectors, routing_approach) = routing::perform_hybrid_routing_if_enabled(
state,
business_profile,
&payment_dsl_input,
+ &backend_input,
+ &fallback_config,
&static_connectors,
static_approach,
)
.await;
- #[cfg(not(all(feature = "v1", feature = "dynamic_routing")))]
- let (connectors, routing_approach) = (static_connectors, static_approach);
-
Ok(routing::RoutingConnectorOutcomeWithApproachAndEligibility {
connectors,
routing_approach,
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index b856e2a021..9d6b17bdda 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -702,9 +702,19 @@ impl RoutingConnectorOutcome {
if self.connectors.is_empty() {
logger::warn!("euclid: {} returned empty connectors, falling back", stage);
routing::log_connectors(stage, fallback);
+ logger::debug!(
+ stage = %stage,
+ routing_approach = ?fallback_approach,
+ "euclid: routing approach after stage"
+ );
(fallback.to_vec(), fallback_approach)
} else {
routing::log_connectors(stage, &self.connectors);
+ logger::debug!(
+ stage = %stage,
+ routing_approach = ?success_approach,
+ "euclid: routing approach after stage"
+ );
(self.connectors, success_approach)
}
}
@@ -780,7 +790,7 @@ impl RoutingStage for StaticRoutingStage {
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")?;
+ .attach_printable("euclid: unable to perform static routing locally")?;
Ok(RoutingConnectorOutcome { connectors })
})
@@ -791,54 +801,8 @@ 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(
+pub async fn perform_static_routing_locally(
state: &SessionState,
business_profile: &domain::Profile,
payment_dsl_input: &routing::PaymentsDslInput<'_>,
@@ -889,7 +853,7 @@ pub async fn perform_static_routing_with_de(
.inspect_err(|err| {
logger::error!(
error=?err,
- "euclid: static routing failed"
+ "euclid: local static routing failed"
);
})
.ok()
@@ -909,43 +873,7 @@ pub async fn perform_static_routing_with_de(
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))
+ Ok((static_connectors, static_approach))
}
pub struct SessionRoutingInput<'a> {
@@ -1301,7 +1229,7 @@ where
.payment_method_type
.as_ref(),
) {
- logger::debug!("euclid: considering pre-routing result");
+ logger::debug!("euclid: checking for pre-routing result");
let pre_routing_input = PreRoutingInput {
pre_routing_results: &routing_data.routing_info.pre_routing_results,
payment_method_type,
@@ -1405,10 +1333,21 @@ impl RoutingConnectorOutcomeWithApproach {
if self.connectors.is_empty() {
logger::warn!("euclid: {} returned empty connectors, falling back", stage);
routing::log_connectors(stage, fallback_connectors);
+ logger::debug!(
+ stage = %stage,
+ routing_approach = ?fallback_approach,
+ "euclid: routing approach after stage"
+ );
(fallback_connectors.to_vec(), fallback_approach)
} else {
+ let routing_approach = self.routing_approach;
routing::log_connectors(stage, &self.connectors);
- (self.connectors, self.routing_approach)
+ logger::debug!(
+ stage = %stage,
+ routing_approach = ?routing_approach,
+ "euclid: routing approach after stage"
+ );
+ (self.connectors, routing_approach)
}
}
@@ -1420,139 +1359,254 @@ impl RoutingConnectorOutcomeWithApproach {
}
}
-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-pub struct DynamicRoutingStage;
+#[cfg(feature = "v1")]
+pub struct HybridRoutingInput<'a> {
+ pub state: &'a SessionState,
+ pub business_profile: &'a domain::Profile,
+ pub payment_dsl_input: &'a routing::PaymentsDslInput<'a>,
+ pub backend_input: &'a backend::BackendInput,
+ pub fallback_config: &'a [routing_types::RoutableConnectorChoice],
+ pub static_connectors: &'a [routing_types::RoutableConnectorChoice],
+ pub static_approach: common_enums::RoutingApproach,
+}
-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-impl DynamicRoutingStage {
- async fn resolve_dynamic_connectors(
+#[cfg(feature = "v1")]
+pub struct HybridRoutingStage;
+
+#[cfg(feature = "v1")]
+impl HybridRoutingStage {
+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+ fn build_dynamic_routing_request(
&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
+ 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()
{
- 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)
+ 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)
}
}
-}
-#[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(not(all(feature = "v1", feature = "dynamic_routing")))]
+ fn build_dynamic_routing_request(
+ &self,
+ _input: &HybridRoutingInput<'_>,
+ ) -> (Option<OpenRouterDecideGatewayRequest>, Option<u8>) {
+ (None, None)
+ }
}
-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-impl RoutingStage for DynamicRoutingStage {
- type Input<'a> = DynamicRoutingInput<'a>;
- type Output = Option<RoutingConnectorOutcomeWithApproach>;
+#[cfg(feature = "v1")]
+impl RoutingStage for HybridRoutingStage {
+ type Input<'a> = HybridRoutingInput<'a>;
+ type Output = 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_request, _dynamic_routing_volume_split) =
+ self.build_dynamic_routing_request(&input);
+
+ let should_include_static_request = input.state.conf.open_router.static_routing_enabled
+ && input.static_approach == common_enums::RoutingApproach::RuleBasedRouting;
+
+ let static_routing_request = if should_include_static_request {
+ Some(utils::build_static_routing_request_for_hybrid(
+ input
+ .business_profile
+ .get_id()
+ .get_string_repr()
+ .to_string(),
+ input.backend_input.clone(),
+ input.fallback_config.to_vec(),
+ )?)
+ } else {
+ 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 outcome = if static_routing_request.is_none() && dynamic_routing_request.is_none() {
+ logger::debug!(
+ "euclid: hybrid routing skipped since both static and dynamic DE flags are disabled"
+ );
+ RoutingConnectorOutcomeWithApproach::empty()
+ } else {
+ let payment_id = input
+ .payment_dsl_input
+ .payment_attempt
+ .payment_id
+ .get_string_repr()
+ .to_string();
+
+ let hybrid_outcome = utils::decision_engine_hybrid_routing(
+ input.state,
+ input.business_profile,
+ payment_id,
+ utils::HybridRoutingRequest {
+ static_routing_request,
+ dynamic_routing_request,
+ },
+ input.static_connectors.to_vec(),
+ )
+ .await?;
- 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(),
+ // Keep legacy diff/selection logs for dashboard compatibility.
+ // Routing behavior remains hybrid-first; this is logging-only parity.
+ utils::compare_and_log_result(
+ hybrid_outcome.connectors.clone(),
+ input.static_connectors.to_vec(),
+ "evaluate_routing".to_string(),
+ );
+ RoutingConnectorOutcomeWithApproach {
+ connectors: hybrid_outcome.connectors,
+ routing_approach: hybrid_outcome.routing_approach.into(),
+ }
};
- 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
+ Ok(outcome)
})
}
fn routing_approach(&self) -> common_enums::RoutingApproach {
- common_enums::RoutingApproach::Other("DynamicRouting".to_string())
+ common_enums::RoutingApproach::Other("HybridRouting".to_string())
}
}
-#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-pub async fn perform_dynamic_routing_if_enabled(
+#[cfg(feature = "v1")]
+pub async fn perform_hybrid_routing_if_enabled(
state: &SessionState,
business_profile: &domain::Profile,
payment_dsl_input: &routing::PaymentsDslInput<'_>,
+ backend_input: &backend::BackendInput,
+ fallback_config: &[routing_types::RoutableConnectorChoice],
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,
- };
+ let stage = HybridRoutingStage;
+ let input = HybridRoutingInput {
+ state,
+ business_profile,
+ payment_dsl_input,
+ backend_input,
+ fallback_config,
+ static_connectors,
+ static_approach: static_approach.clone(),
+ };
- 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)
+ let is_decision_engine_cutover_enabled = matches!(
+ utils::get_routing_result_source(state, business_profile).await,
+ Some(api_models::routing::RoutingResultSource::DecisionEngine)
+ );
+
+ if is_decision_engine_cutover_enabled {
+ let hybrid_stage_outcome = stage
+ .route(input)
+ .await
+ .inspect_err(|error| {
+ logger::error!(
+ error=?error,
+ "euclid: hybrid routing failed"
+ );
+ })
+ .unwrap_or_else(|_| RoutingConnectorOutcomeWithApproach::empty());
+
+ let selected_source = if hybrid_stage_outcome.connectors.is_empty() {
+ "hyperswitch_static"
+ } else {
+ "decision_engine"
+ };
+
+ logger::info!(
+ business_profile_id=?business_profile.get_id(),
+ routing_source = %selected_source,
+ "decision_engine_euclid: selected routing source after hybrid stage"
+ );
+
+ hybrid_stage_outcome.resolve_or_fallback(
+ "hybrid-routing",
+ static_connectors,
+ static_approach,
+ )
+ } else {
+ logger::debug!(
+ business_profile_id=?business_profile.get_id(),
+ "decision_engine_euclid: cutover not enabled, using static routing result"
+ );
+ logger::info!(
+ business_profile_id=?business_profile.get_id(),
+ routing_source = "hyperswitch_static",
+ "decision_engine_euclid: selected routing source after hybrid stage"
+ );
+ (static_connectors.to_vec(), static_approach)
+ }
}
pub async fn static_routing_v1(
@@ -2054,8 +2108,14 @@ pub async fn refresh_cgraph_cache(
.into_iter()
.filter(|(key, _)| key != "default")
.map(|(key, value)| {
- let key = api_enums::RoutableConnectors::from_str(&key)
- .map_err(|_| errors::RoutingError::InvalidConnectorName(key))?;
+ let key = api_enums::RoutableConnectors::from_str(&key).map_err(|error| {
+ logger::error!(
+ error=?error,
+ connector_name = %key,
+ "euclid: invalid connector name in pm_filters config"
+ );
+ errors::RoutingError::InvalidConnectorName(key)
+ })?;
Ok((key, value.foreign_into()))
})
diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs
index 4b5ced7c01..d5a630d3f4 100644
--- a/crates/router/src/core/payments/routing/utils.rs
+++ b/crates/router/src/core/payments/routing/utils.rs
@@ -67,6 +67,32 @@ pub struct ConfigApiClient;
pub struct SRApiClient;
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct HybridRoutingRequest {
+ pub static_routing_request: Option<RoutingEvaluateRequest>,
+ pub dynamic_routing_request: Option<or_types::OpenRouterDecideGatewayRequest>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct HybridRoutingResponse {
+ pub static_routing: Option<RoutingEvaluateResponse>,
+ pub dynamic_routing: Option<DynamicRoutingWrapper>,
+ pub evaluated_connectors: Option<Vec<DeRoutableConnectorChoice>>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct DynamicRoutingWrapper {
+ pub status: String,
+ pub decision: Option<or_types::DecideGatewayResponse>,
+ pub fallback_connectors: Option<Vec<DeRoutableConnectorChoice>>,
+}
+
+#[derive(Clone, Debug)]
+pub struct HybridRoutingOutcome {
+ pub connectors: Vec<RoutableConnectorChoice>,
+ pub routing_approach: RoutingApproach,
+}
+
pub async fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>(
state: &SessionState,
http_method: services::Method,
@@ -304,6 +330,188 @@ impl DecisionEngineApiHandler for SRApiClient {
const EUCLID_API_TIMEOUT: u64 = 5;
+fn convert_fallback_to_de_choices(
+ fallback_output: Vec<RoutableConnectorChoice>,
+) -> Vec<DeRoutableConnectorChoice> {
+ fallback_output
+ .into_iter()
+ .map(|connector| DeRoutableConnectorChoice {
+ gateway_name: connector.connector,
+ gateway_id: connector.merchant_connector_id,
+ })
+ .collect()
+}
+
+pub fn build_static_routing_request_for_hybrid(
+ created_by: String,
+ input: BackendInput,
+ fallback_output: Vec<RoutableConnectorChoice>,
+) -> RoutingResult<RoutingEvaluateRequest> {
+ convert_backend_input_to_routing_eval(
+ created_by,
+ input,
+ convert_fallback_to_de_choices(fallback_output),
+ )
+}
+
+fn infer_hybrid_routing_approach(response: &HybridRoutingResponse) -> RoutingApproach {
+ response
+ .dynamic_routing
+ .as_ref()
+ .and_then(|dynamic_routing| dynamic_routing.decision.as_ref())
+ .and_then(|decision| decision.routing_approach.as_deref())
+ .map(RoutingApproach::from_decision_engine_approach)
+ .unwrap_or_else(|| {
+ if response.static_routing.is_some() {
+ RoutingApproach::StaticRouting
+ } else {
+ RoutingApproach::Default
+ }
+ })
+}
+
+pub fn normalize_hybrid_routing_response(
+ response: &HybridRoutingResponse,
+) -> RoutingResult<HybridRoutingOutcome> {
+ let outcome = if let Some(evaluated_connectors) = response
+ .evaluated_connectors
+ .as_ref()
+ .filter(|connectors| !connectors.is_empty())
+ {
+ let connectors = evaluated_connectors
+ .iter()
+ .cloned()
+ .map(RoutableConnectorChoice::from)
+ .collect();
+
+ HybridRoutingOutcome {
+ connectors,
+ routing_approach: infer_hybrid_routing_approach(response),
+ }
+ } else if let Some(static_routing_response) = response.static_routing.as_ref() {
+ let static_output_connectors = extract_de_output_connectors(
+ static_routing_response.output.clone(),
+ )
+ .map_err(|error| {
+ logger::error!(
+ error=?error,
+ "euclid: failed to extract connector from hybrid static output"
+ );
+ error
+ })?;
+
+ let static_connectors = transform_de_output_for_router(
+ static_output_connectors,
+ static_routing_response.evaluated_output.clone(),
+ )
+ .map_err(|error| {
+ logger::error!(
+ error=?error,
+ "euclid: failed to transform connectors from hybrid static output"
+ );
+ error
+ })?;
+
+ HybridRoutingOutcome {
+ connectors: static_connectors,
+ routing_approach: RoutingApproach::StaticRouting,
+ }
+ } else {
+ logger::debug!(
+ "euclid: hybrid routing response did not include usable evaluated connectors or static output; returning empty connector set"
+ );
+ HybridRoutingOutcome {
+ connectors: Vec::new(),
+ routing_approach: RoutingApproach::Default,
+ }
+ };
+
+ Ok(outcome)
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(untagged)]
+enum HybridErrorResponse {
+ Static(DeErrorResponse),
+ Dynamic(or_types::ErrorResponse),
+}
+
+impl DecisionEngineErrorsInterface for HybridErrorResponse {
+ fn get_error_message(&self) -> String {
+ match self {
+ Self::Static(error) => error.get_error_message(),
+ Self::Dynamic(error) => error.get_error_message(),
+ }
+ }
+
+ fn get_error_code(&self) -> String {
+ match self {
+ Self::Static(error) => error.get_error_code(),
+ Self::Dynamic(error) => error.get_error_code(),
+ }
+ }
+
+ fn get_error_data(&self) -> Option<String> {
+ match self {
+ Self::Static(error) => error.get_error_data(),
+ Self::Dynamic(error) => error.get_error_data(),
+ }
+ }
+}
+
+pub async fn decision_engine_hybrid_routing(
+ state: &SessionState,
+ business_profile: &domain::Profile,
+ payment_id: String,
+ hybrid_request: HybridRoutingRequest,
+ _fallback_connectors: Vec<RoutableConnectorChoice>,
+) -> RoutingResult<HybridRoutingOutcome> {
+ let routing_events_wrapper = RoutingEventsWrapper::new(
+ state.tenant.tenant_id.clone(),
+ state.request_id.clone(),
+ payment_id,
+ business_profile.get_id().to_owned(),
+ business_profile.merchant_id.to_owned(),
+ "DecisionEngine: Hybrid Routing".to_string(),
+ Some(hybrid_request.clone()),
+ true,
+ false,
+ );
+
+ let event_response = build_and_send_decision_engine_http_request::<_, _, HybridErrorResponse>(
+ state,
+ services::Method::Post,
+ "routing/hybrid",
+ Some(hybrid_request),
+ Some(EUCLID_API_TIMEOUT),
+ "parsing response",
+ Some(routing_events_wrapper),
+ )
+ .await?;
+
+ let hybrid_response: HybridRoutingResponse =
+ event_response
+ .response
+ .ok_or(errors::RoutingError::OpenRouterError(
+ "euclid: response from decision engine hybrid API is empty".to_string(),
+ ))?;
+
+ let outcome = normalize_hybrid_routing_response(&hybrid_response)?;
+ let mut routing_event =
+ event_response
+ .event
+ .ok_or(errors::RoutingError::RoutingEventsError {
+ message: "euclid: routing event not found in hybrid events response".to_string(),
+ status_code: 500,
+ })?;
+
+ routing_event.set_routing_approach(outcome.routing_approach.to_string());
+ routing_event.set_routable_connectors(outcome.connectors.clone());
+ state.event_handler().log_event(&routing_event);
+
+ Ok(outcome)
+}
+
pub async fn perform_decision_euclid_routing(
state: &SessionState,
input: BackendInput,
@@ -314,13 +522,7 @@ pub async fn perform_decision_euclid_routing(
logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation");
let mut events_wrapper = events_wrapper;
- let fallback_output = fallback_output
- .into_iter()
- .map(|c| DeRoutableConnectorChoice {
- gateway_name: c.connector,
- gateway_id: c.merchant_connector_id,
- })
- .collect::<Vec<_>>();
+ let fallback_output = convert_fallback_to_de_choices(fallback_output);
let routing_request =
convert_backend_input_to_routing_eval(created_by, input, fallback_output)?;
@@ -378,7 +580,13 @@ pub fn transform_de_output_for_router(
// Add remaining connectors from de_output (only if not already seen), for fallback
for conn in de_output {
- let key = RoutableConnectors::from_str(&conn.gateway_name).map_err(|_| {
+ let connector_name = conn.gateway_name.clone();
+ let key = RoutableConnectors::from_str(&connector_name).map_err(|error| {
+ logger::error!(
+ error=?error,
+ connector_name = %connector_name,
+ "euclid: failed to parse connector name from decision engine output"
+ );
errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
@@ -767,9 +975,15 @@ impl RoutingEq<Self> for RoutableConnectorChoice {
pub fn to_json_string<T: Serialize>(value: &T) -> String {
serde_json::to_string(value)
- .map_err(|_| errors::RoutingError::GenericConversionError {
- from: "T".to_string(),
- to: "JsonValue".to_string(),
+ .map_err(|error| {
+ logger::error!(
+ error=?error,
+ "euclid: failed to serialize value to json string"
+ );
+ errors::RoutingError::GenericConversionError {
+ from: "T".to_string(),
+ to: "JsonValue".to_string(),
+ }
})
.unwrap_or_default()
}
@@ -1184,9 +1398,16 @@ impl TryFrom<ConnectorInfo> for DeRoutableConnectorChoice {
.transpose()?;
let gateway_name = RoutableConnectors::from_str(&c.gateway_name)
- .map_err(|_| errors::RoutingError::GenericConversionError {
- from: "String".to_string(),
- to: "RoutableConnectors".to_string(),
+ .map_err(|error| {
+ logger::error!(
+ error=?error,
+ gateway_name = %c.gateway_name,
+ "euclid: unable to convert connector name to RoutableConnectors"
+ );
+ errors::RoutingError::GenericConversionError {
+ from: "String".to_string(),
+ to: "RoutableConnectors".to_string(),
+ }
})
.attach_printable("unable to convert connector name to RoutableConnectors")?;
@@ -1498,16 +1719,11 @@ fn stringify_choice(c: RoutableConnectorChoice) -> ConnectorInfo {
)
}
-pub async fn select_routing_result<T>(
+pub async fn get_routing_result_source(
state: &SessionState,
business_profile: &business_profile::Profile,
- hyperswitch_result: T,
- de_result: T,
-) -> T
-where
- T: Clone + IntoIterator,
-{
- let routing_result_source: Option<api_routing::RoutingResultSource> = state
+) -> Option<api_routing::RoutingResultSource> {
+ state
.store
.find_config_by_key(&format!(
"routing_result_source_{0}",
@@ -1515,7 +1731,19 @@ where
))
.await
.map(|c| c.config.parse_enum("RoutingResultSource").ok())
- .unwrap_or(None);
+ .unwrap_or(None)
+}
+
+pub async fn select_routing_result<T>(
+ state: &SessionState,
+ business_profile: &business_profile::Profile,
+ hyperswitch_result: T,
+ de_result: T,
+) -> T
+where
+ T: Clone + IntoIterator,
+{
+ let routing_result_source = get_routing_result_source(state, business_profile).await;
if let Some(api_routing::RoutingResultSource::DecisionEngine) = routing_result_source {
logger::debug!(