Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor(core): interpolate params with their specific values #6448

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions config/development.toml
Original file line number Diff line number Diff line change
Expand Up @@ -766,3 +766,7 @@ card_networks = "Visa, AmericanExpress, Mastercard"

[network_tokenization_supported_connectors]
connector_list = "cybersource"

[grpc_client.dynamic_routing_client]
host = "localhost"
port = 7000
6 changes: 5 additions & 1 deletion crates/api_models/src/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -615,8 +615,12 @@ impl Default for SuccessBasedRoutingConfig {
pub enum SuccessBasedRoutingConfigParams {
PaymentMethod,
PaymentMethodType,
Currency,
AuthenticationType,
Currency,
PaymentType,
Country,
CardNetwork,
CardBin,
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
Expand Down
32 changes: 17 additions & 15 deletions crates/external_services/src/grpc_client/dynamic_routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
) -> DynamicRoutingResult<CalSuccessRateResponse>;
/// To update the success rate with the given label
Expand All @@ -107,23 +108,24 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> {
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
) -> DynamicRoutingResult<CalSuccessRateResponse> {
let params = success_rate_based_config
.params
.map(|vec| {
vec.into_iter().fold(String::new(), |mut acc_str, params| {
if !acc_str.is_empty() {
acc_str.push(':')
}
acc_str.push_str(params.to_string().as_str());
acc_str
})
})
.get_required_value("params")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "params".to_string(),
})?;
// let params = success_rate_based_config
// .params
// .map(|vec| {
// vec.into_iter().fold(String::new(), |mut acc_str, params| {
// if !acc_str.is_empty() {
// acc_str.push(':')
// }
// acc_str.push_str(params.to_string().as_str());
// acc_str
// })
// })
// .get_required_value("params")
// .change_context(DynamicRoutingError::MissingRequiredField {
// field: "params".to_string(),
// })?;

let labels = label_input
.into_iter()
Expand Down
2 changes: 1 addition & 1 deletion crates/router/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ license.workspace = true

[features]
default = ["common_default", "v1"]
common_default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls", "partial-auth", "km_forward_x_request_id"]
common_default = ["dynamic_routing","kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls", "partial-auth", "km_forward_x_request_id"]
olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"]
tls = ["actix-web/rustls-0_22"]
email = ["external_services/email", "scheduler/email", "olap"]
Expand Down
13 changes: 9 additions & 4 deletions crates/router/src/core/payments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5587,10 +5587,15 @@ where
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
let connectors = {
if business_profile.dynamic_routing_algorithm.is_some() {
routing::perform_success_based_routing(state, connectors.clone(), business_profile)
.await
.map_err(|e| logger::error!(success_rate_routing_error=?e))
.unwrap_or(connectors)
routing::perform_success_based_routing(
state,
connectors.clone(),
business_profile,
payment_data,
)
.await
.map_err(|e| logger::error!(success_rate_routing_error=?e))
.unwrap_or(connectors)
} else {
connectors
}
Expand Down
79 changes: 77 additions & 2 deletions crates/router/src/core/payments/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ use rand::{
use rustc_hash::FxHashMap;
use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE};

use super::{OperationSessionGetters, OperationSessionSetters};
#[cfg(feature = "v2")]
use crate::core::admin;
#[cfg(feature = "payouts")]
Expand Down Expand Up @@ -1236,11 +1237,16 @@ pub fn make_dsl_input_for_surcharge(

/// success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_success_based_routing(
pub async fn perform_success_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
payment_data: &D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let success_based_dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef =
business_profile
.dynamic_routing_algorithm
Expand Down Expand Up @@ -1293,6 +1299,9 @@ pub async fn perform_success_based_routing(
.change_context(errors::RoutingError::SuccessBasedRoutingConfigError)
.attach_printable("unable to fetch success_rate based dynamic routing configs")?;

let success_based_routing_config_params =
interpolate_success_based_routing_params(success_based_routing_configs, payment_data);

let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id(
&state.tenant.redis_key_prefix,
business_profile.get_id().get_string_repr(),
Expand Down Expand Up @@ -1344,3 +1353,69 @@ pub async fn perform_success_based_routing(
Ok(routable_connectors)
}
}

pub async fn interpolate_success_based_routing_params<F, D>(
success_rate_based_config: api_routing::SuccessBasedRoutingConfig,
payment_data: &D,
) -> Vec<String>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let mut res = Vec::new();
for param in success_rate_based_config.params.unwrap() {
let val: String = match param {
api_routing::SuccessBasedRoutingConfigParams::PaymentMethod => payment_data
.get_payment_attempt()
.payment_method
.unwrap()
.to_string(),
api_routing::SuccessBasedRoutingConfigParams::PaymentMethodType => payment_data
.get_payment_attempt()
.get_payment_method_type()
.unwrap()
.to_string(),
api_routing::SuccessBasedRoutingConfigParams::AuthenticationType => payment_data
.get_payment_attempt()
.authentication_type
.unwrap()
.to_string(),
api_routing::SuccessBasedRoutingConfigParams::Currency => {
payment_data.get_currency().to_string()
}
api_routing::SuccessBasedRoutingConfigParams::Country => payment_data
.get_billing_address()
.unwrap()
.address
.unwrap()
.country
.unwrap()
.to_string(),
api_routing::SuccessBasedRoutingConfigParams::PaymentType => todo!(),
api_routing::SuccessBasedRoutingConfigParams::CardNetwork => payment_data
.get_payment_attempt()
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string())
.unwrap(),
api_routing::SuccessBasedRoutingConfigParams::CardBin => payment_data
.get_payment_attempt()
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_number"))
.and_then(|network| network.as_str())
.map(|network| network.to_string())
.unwrap(),
};
res.push(val);
}
res
}
Loading