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): preferred-connector routing for interac — pin the customer's last successful connector (#14412)
Prajjwal Kumarb1f8bf97f4ee
diff --git a/api-reference/decision_engine_openapi-specs.json b/api-reference/decision_engine_openapi-specs.jsonindex bace3881b3..6a6a48be2d 100644--- a/api-reference/decision_engine_openapi-specs.json+++ b/api-reference/decision_engine_openapi-specs.json@@ -4829,12 +4829,10 @@"type": "string"}},- "preferredGateway": {- "type": [- "string",- "null"- ],- "description": "Pins routing to a specific gateway when set."+ "preferredConnectors": {+ "type": ["array", "null"],+ "items": { "type": "string" },+ "description": "Ordered connector:mca_id preferences from the customer's profile-scoped history. The first entry is considered; health and eligibility checks still apply."},"paymentType": {"type": "string",diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex b9ffc3df24..f4ada6d0d3 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -32293,6 +32293,17 @@"description": "Currency code for the payment","example": "USD"},+ "preferredConnectors": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Ordered preferred connector account identities in `connector:mca_id` format.",+ "example": [+ "adyen:mca_5678"+ ],+ "nullable": true+ },"paymentType": {"type": "string","description": "Type of payment transaction being processed",diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex a41ae6cd2d..05c6b6d0cf 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2671,6 +2671,8 @@ pt_mapping_outgoing_connector_webhooks = { value = { default_mapping = { frequen"decision_engine","hyperswitch_routing",], type = "string" }, description = "Source of routing result: decision_engine (external DE) or hyperswitch_routing (inbuilt)", change_reason = "Initial setup" }+"routing.preferred_connectors_routing_enabled" = { value = false, schema = { type = "boolean" }, description = "Whether preferred-connectors routing (pin returning customers to their last successful connector) is enabled for a profile", change_reason = "Initial setup" }+"routing.preferred_connectors_enabled_payment_method_types" = { value = "interac", schema = { type = "string" }, description = "Comma-separated payment method types eligible for preferred-connectors routing", change_reason = "Initial setup" }"vaulting.save_wallet_decrypted_data" = { value = false, schema = { type = "boolean" }, description = "Whether to save wallet decrypted data", change_reason = "Initial setup" }"vaulting.fingerprint_secret" = { value = "", schema = { type = "string" }, description = "Fingerprint secret used as a migration fallback for merchant accounts", change_reason = "Retain during merchant account migration" }"payments.should_call_gsm" = { value = false, schema = { type = "boolean" }, description = "Whether to call GSM (Global Status Mapping) for auto-retries on payment failure", change_reason = "Initial setup" }diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rsindex 222398cf23..c8c21cbf38 100644--- a/crates/api_models/src/open_router.rs+++ b/crates/api_models/src/open_router.rs@@ -157,7 +157,9 @@ pub struct PaymentInfo {#[schema(value_type = String, example = "USD")]pub currency: Currency,// customerId: Option<ETCu::CustomerId>,- // preferredGateway: Option<ETG::Gateway>,+ /// Ordered preferred connector account identities in `connector:mca_id` format.+ #[schema(value_type = Option<Vec<String>>, example = json!(["adyen:mca_5678"]))]+ pub preferred_connectors: Option<Vec<String>>,/// Type of payment transaction being processed#[schema(value_type = String, example = "ORDER_PAYMENT")]pub payment_type: String,@@ -642,3 +644,38 @@ pub enum AlgorithmType {Elimination,DebitRouting,}++#[cfg(test)]+#[allow(clippy::expect_used, clippy::indexing_slicing)]+mod preferred_connectors_tests {+ use serde_json::json;++ use super::PaymentInfo;++ #[test]+ fn preferred_connectors_uses_decision_engine_wire_contract() {+ let payload = json!({+ "paymentId": "pay_12345",+ "amount": 100,+ "currency": "CAD",+ "preferredConnectors": ["loonio:mca_one"],+ "paymentType": "ORDER_PAYMENT",+ "paymentMethodType": "interac",+ "paymentMethod": "bank_redirect"+ });+ let payment: PaymentInfo = serde_json::from_value(payload).expect("valid DE payment info");+ assert_eq!(+ payment.preferred_connectors,+ Some(vec!["loonio:mca_one".to_string()])+ );+ let serialized = serde_json::to_value(payment).expect("serialize DE payment info");+ assert_eq!(serialized["preferredConnectors"], json!(["loonio:mca_one"]));+ for removed_field in [+ "preferredConnector",+ "preferredGateways",+ "preferredGateway",+ ] {+ assert!(serialized.get(removed_field).is_none());+ }+ }+}diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rsindex 8254cc5973..1fc6b2acb4 100644--- a/crates/diesel_models/src/customers.rs+++ b/crates/diesel_models/src/customers.rs@@ -35,6 +35,7 @@ pub struct CustomerNew {pub last_modified_by: Option<String>,pub document_details: Option<Encryption>,pub id: Option<common_utils::id_type::GlobalCustomerId>,+ pub preferred_connectors: Option<pii::SecretSerdeValue>,}#[cfg(feature = "v1")]@@ -68,6 +69,7 @@ impl From<CustomerNew> for Customer {created_by: customer_new.created_by,last_modified_by: customer_new.last_modified_by,id: customer_new.id,+ preferred_connectors: customer_new.preferred_connectors,}}}@@ -96,6 +98,7 @@ pub struct CustomerNew {pub last_modified_by: Option<String>,pub document_details: Option<Encryption>,pub id: common_utils::id_type::GlobalCustomerId,+ pub preferred_connectors: Option<pii::SecretSerdeValue>,pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,pub default_billing_address: Option<Encryption>,pub default_shipping_address: Option<Encryption>,@@ -137,6 +140,7 @@ impl From<CustomerNew> for Customer {created_by: customer_new.created_by,last_modified_by: customer_new.last_modified_by,customer_id: customer_new.customer_id,+ preferred_connectors: customer_new.preferred_connectors,}}}@@ -167,6 +171,7 @@ pub struct Customer {pub last_modified_by: Option<String>,pub document_details: Option<Encryption>,pub id: Option<common_utils::id_type::GlobalCustomerId>,+ pub preferred_connectors: Option<pii::SecretSerdeValue>,}#[cfg(feature = "v2")]@@ -193,6 +198,7 @@ pub struct Customer {pub last_modified_by: Option<String>,pub document_details: Option<Encryption>,pub id: common_utils::id_type::GlobalCustomerId,+ pub preferred_connectors: Option<pii::SecretSerdeValue>,pub merchant_reference_id: Option<common_utils::id_type::CustomerId>,pub default_billing_address: Option<Encryption>,pub default_shipping_address: Option<Encryption>,@@ -231,6 +237,7 @@ pub struct CustomerUpdateInternal {pub tax_registration_id: Option<Encryption>,pub last_modified_by: Option<String>,pub document_details: Option<Encryption>,+ pub preferred_connectors: Option<pii::SecretSerdeValue>,}#[cfg(feature = "v2")]diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 68db224ce1..d789ae4067 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -512,6 +512,7 @@ diesel::table! {document_details -> Nullable<Bytea>,#[max_length = 64]id -> Nullable<Varchar>,+ preferred_connectors -> Nullable<Jsonb>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex fe15ff6083..8b985e3a06 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -494,6 +494,7 @@ diesel::table! {document_details -> Nullable<Bytea>,#[max_length = 64]id -> Varchar,+ preferred_connectors -> Nullable<Jsonb>,#[max_length = 64]merchant_reference_id -> Nullable<Varchar>,default_billing_address -> Nullable<Bytea>,diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rsindex 93780a4979..6836852d1c 100644--- a/crates/hyperswitch_domain_models/src/customer.rs+++ b/crates/hyperswitch_domain_models/src/customer.rs@@ -66,6 +66,7 @@ pub struct Customer {pub document_details: OptionalEncryptableValue,pub created_by: Option<CreatedBy>,pub last_modified_by: Option<CreatedBy>,+ pub preferred_connectors: Option<pii::SecretSerdeValue>,}#[cfg(feature = "v2")]@@ -97,6 +98,7 @@ pub struct Customer {pub document_details: OptionalEncryptableValue,pub created_by: Option<CreatedBy>,pub last_modified_by: Option<CreatedBy>,+ pub preferred_connectors: Option<pii::SecretSerdeValue>,}/// A customer view containing only fields that do not require key-manager decryption.@@ -161,6 +163,7 @@ impl Customer {document_details,created_by,last_modified_by,+ preferred_connectors: None,}}@@ -288,6 +291,10 @@ pub enum CustomerUpdate {default_payment_method_id: Option<Option<String>>,last_modified_by: Option<String>,},+ UpdatePreferredConnectors {+ preferred_connectors: Option<pii::SecretSerdeValue>,+ last_modified_by: Option<String>,+ },}pub struct CustomerListConstraints {diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 50266fec0c..754f169560 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -533,6 +533,12 @@ pub mod superposition {pub const PAYOUT_FRM_CALL: &str = "payouts.payout_frm_call";/// Maximum number of card issuers a list request readspub const CARD_ISSUER_LIST_MAX_LIMIT: &str = "card_issuer.list_max_limit";+ /// Preferred-connector routing enablement configuration key per profile+ pub const PREFERRED_CONNECTORS_ROUTING_ENABLED: &str =+ "routing.preferred_connectors_routing_enabled";+ /// Payment method types eligible for preferred-connectors routing (comma-separated)+ pub const PREFERRED_CONNECTORS_ENABLED_PAYMENT_METHOD_TYPES: &str =+ "routing.preferred_connectors_enabled_payment_method_types";/// Payout blocklist guard configuration keypub const PAYOUT_BLOCKLIST_GUARD: &str = "payouts.payout_blocklist_guard";}diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex ddc7ce7b49..59e4151f31 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -1060,6 +1060,36 @@ impl DatabaseBackedConfig for CardIssuerListMaxLimit {const KEY: &'static str = "card_issuer_list_max_limit";}+config! {+ superposition_key = PREFERRED_CONNECTORS_ROUTING_ENABLED,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ targeting_key = id_type::ProfileId+}++config! {+ superposition_key = PREFERRED_CONNECTORS_ENABLED_PAYMENT_METHOD_TYPES,+ output = String,+ default = String::from("interac"),+ requires = dimension_state::DimensionsGlobal,+ targeting_key = id_type::MerchantId+}++impl DatabaseBackedConfig for PreferredConnectorsEnabledPaymentMethodTypes {+ const KEY: &'static str = "preferred_connectors_enabled_payment_method_types";+}++impl DatabaseBackedConfig for PreferredConnectorsRoutingEnabled {+ const KEY: &'static str = "preferred_connectors_routing_enabled";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_profile_id()+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))+ }+}+config! {superposition_key = PAYOUT_BLOCKLIST_GUARD,output = bool,diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rsindex 8c3352d339..f716256467 100644--- a/crates/router/src/core/customers.rs+++ b/crates/router/src/core/customers.rs@@ -419,6 +419,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {document_details: None,created_by: initiator.and_then(|initiator| initiator.to_created_by()),last_modified_by: initiator.and_then(|initiator| initiator.to_created_by()),+ preferred_connectors: None,})}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 390b7cda95..a08bf7d3f2 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -308,7 +308,7 @@ where.await?;// Update customer at provider level before update_trackers- operation+ let _updated_customer = operation.to_domain()?.update_customer(&updated_state,@@ -419,7 +419,7 @@ where.await?;// Update customer at provider level before update_trackers- operation+ let _updated_customer = operation.to_domain()?.update_customer(&updated_state,@@ -736,7 +736,7 @@ where&payment_data.get_payment_intent().clone(),)?;- let (operation, customer) = operation+ let (operation, mut customer) = operation.to_domain()?// get_customer_details.get_or_create_customer_details(@@ -822,6 +822,9 @@ wheremandate_type,&dimensions,call_connector_action.clone(),+ customer+ .as_ref()+ .and_then(|customer| customer.preferred_connectors.clone()),).await?;@@ -1063,12 +1066,12 @@ where.await?;// Update customer at provider level before update_trackers- operation+ customer = operation.to_domain()?.update_customer(&updated_state,platform.get_provider(),- customer.clone(),+ customer,updated_customer,).await?;@@ -1124,6 +1127,8 @@ where.update_tracker(state,platform.get_processor(),+ platform.get_provider(),+ customer.as_ref(),payment_data,router_data,&locale,@@ -1252,12 +1257,12 @@ where.await?;// Update customer at provider level before update_trackers- operation+ customer = operation.to_domain()?.update_customer(&updated_state,platform.get_provider(),- customer.clone(),+ customer,updated_customer,).await?;@@ -1298,7 +1303,7 @@ where.await;if config_bool && router_data.should_call_gsm() {- router_data = retry::do_gsm_actions(+ (router_data, customer) = retry::do_gsm_actions(state,req_state.clone(),&mut payment_data,@@ -1307,7 +1312,7 @@ whererouter_data,platform,&operation,- &customer,+ customer,&validate_result,schedule_time,#[cfg(feature = "frm")]@@ -1351,6 +1356,8 @@ where.update_tracker(state,platform.get_processor(),+ platform.get_provider(),+ customer.as_ref(),payment_data,router_data,&locale,@@ -1729,7 +1736,7 @@ whereNone};- let (operation, _customer) = operation+ let (operation, customer) = operation.to_domain()?.get_or_create_customer_details(state,@@ -1781,6 +1788,8 @@ where.update_tracker(state,platform.get_processor(),+ platform.get_provider(),+ customer.as_ref(),payment_data,router_data,&locale,@@ -3093,6 +3102,8 @@ wheremandate_type,&dimensions,call_connector_action.clone(),+ // The customer is fetched after connector selection in this flow.+ None,).await?;@@ -3312,6 +3323,8 @@ where.update_tracker(state,platform.get_processor(),+ platform.get_provider(),+ customer.as_ref(),payment_data,router_data,&locale,@@ -11530,6 +11543,7 @@ pub async fn choose_connector<F, Req, D>(mandate_type: Option<api::MandateTransactionType>,dimensions: &DimensionsWithProcessorAndProviderMerchantIdAndProfileId,call_connector_action: CallConnectorAction,+ customer_preferred_connectors: Option<pii::SecretSerdeValue>,) -> RouterResult<Option<ConnectorCallType>>whereF: Send + Clone + 'static,@@ -11604,6 +11618,7 @@ wheredimensions,fallback_config,backend_input,+ customer_preferred_connectors,).await?}@@ -11621,6 +11636,7 @@ wheredimensions,fallback_config,backend_input,+ customer_preferred_connectors,).await?}@@ -11885,6 +11901,7 @@ pub async fn perform_routing_for_connector_selection<F, D>(dimensions: &DimensionsWithProcessorAndProviderMerchantIdAndProfileId,fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,backend_input: dsl_inputs::BackendInput,+ customer_preferred_connectors: Option<pii::SecretSerdeValue>,) -> RouterResult<ConnectorCallType>whereF: Send + Clone + 'static,@@ -11941,6 +11958,7 @@ wherefallback_config,backend_input,should_use_modular_pm_path,+ customer_preferred_connectors,).await?;@@ -12122,6 +12140,39 @@ pub async fn decide_connector(}}+/// Returns the global payment-method allowlist shared by preferred-connector reads and writes.+#[cfg(feature = "v1")]+pub async fn preferred_connectors_enabled_payment_method_types(+ state: &SessionState,+) -> Vec<String> {+ let dimensions: crate::core::configs::dimension_state::DimensionsGlobal = Dimensions::new();+ dimensions+ .get_preferred_connectors_enabled_payment_method_types(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await+ .split(',')+ .map(|pmt| pmt.trim().to_string())+ .filter(|pmt| !pmt.is_empty())+ .collect()+}++/// Looks up a profile's connector in the stored preferences for one payment method type.+#[cfg(feature = "v1")]+fn preferred_connector_for_profile(+ value: &serde_json::Value,+ payment_method_type: &str,+ profile_id: &str,+) -> Option<String> {+ value+ .get(payment_method_type)?+ .as_array()?+ .iter()+ .find_map(|entry| entry.get(profile_id)?.as_str().map(str::to_string))+}+#[allow(clippy::too_many_arguments)]#[cfg(feature = "v1")]pub async fn decide_connector<F, D>(@@ -12137,6 +12188,7 @@ pub async fn decide_connector<F, D>(fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,backend_input: dsl_inputs::BackendInput,is_payment_method_modular_allowed: bool,+ customer_preferred_connectors: Option<pii::SecretSerdeValue>,) -> RouterResult<ConnectorCallType>whereF: Send + Clone + 'static,@@ -12185,6 +12237,20 @@ wherereturn Ok(connector);}+ let enabled_payment_method_types =+ preferred_connectors_enabled_payment_method_types(&state).await;+ let preferred_connector = payment_data+ .get_payment_attempt()+ .payment_method_type+ .map(|payment_method_type| payment_method_type.to_string())+ .filter(|payment_method_type| enabled_payment_method_types.contains(payment_method_type))+ .and_then(|payment_method_type| {+ let profile_id = business_profile.get_id().get_string_repr();+ customer_preferred_connectors.as_ref().and_then(|value| {+ preferred_connector_for_profile(value.peek(), &payment_method_type, profile_id)+ })+ });+let transaction_data = core_routing::PaymentsDslInput::new(payment_data.get_setup_mandate(),payment_data.get_payment_attempt(),@@ -12259,6 +12325,7 @@ wheretxn_data,backend_input,fallback.clone(),+ preferred_connector,).await.inspect_err(|err| {@@ -13254,6 +13321,7 @@ pub async fn static_dynamic_routing_v1_for_payments(payment_dsl_input: core_routing::PaymentsDslInput<'_>,backend_input: euclid::backend::BackendInput,fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,+ preferred_connector: Option<String>,) -> RouterResult<routing::RoutingConnectorOutcomeWithApproachAndEligibility> {let (static_connectors, static_approach) = routing::perform_static_routing_locally(state,@@ -13273,6 +13341,7 @@ pub async fn static_dynamic_routing_v1_for_payments(&fallback_config,&static_connectors,static_approach,+ preferred_connector,).await;diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rsindex d2768ad855..0e71991451 100644--- a/crates/router/src/core/payments/operations.rs+++ b/crates/router/src/core/payments/operations.rs@@ -333,10 +333,10 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {&'a self,_db: &'a SessionState,_provider: &domain::Provider,- _customer: Option<domain::Customer>,+ customer: Option<domain::Customer>,_updated_customer: Option<storage::CustomerUpdate>,- ) -> RouterResult<()> {- Ok(())+ ) -> RouterResult<Option<domain::Customer>> {+ Ok(customer)}#[cfg(feature = "v2")]@@ -618,6 +618,8 @@ pub trait PostUpdateTracker<F, D, R: Send>: Send {&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,payment_data: D,response: types::RouterData<F, R, PaymentsResponseData>,locale: &Option<String>,diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex baf70dd053..a975f9d79f 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -1138,9 +1138,9 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forprovider: &domain::Provider,customer: Option<domain::Customer>,updated_customer: Option<storage::CustomerUpdate>,- ) -> RouterResult<()> {- if let Some((updated_customer, customer)) = updated_customer.zip(customer) {- state+ ) -> RouterResult<Option<domain::Customer>> {+ match (customer, updated_customer) {+ (Some(customer), Some(updated_customer)) => state.store.update_customer_by_customer_id_merchant_id(customer.get_id().to_owned(),@@ -1152,9 +1152,10 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for).await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update CustomerConnector in customer")?;+ .attach_printable("Failed to update CustomerConnector in customer")+ .map(Some),+ (customer, _) => Ok(customer),}- Ok(())}#[instrument(skip_all)]diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rsindex 17bb548e65..783e4f3553 100644--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs@@ -453,24 +453,27 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfprovider: &domain::Provider,customer: Option<domain::Customer>,updated_customer: Option<storage::CustomerUpdate>,- ) -> RouterResult<()> {- if let Some((customer, updated_customer)) = customer.zip(updated_customer) {- let customer_id = customer.get_id().clone();-- let _updated_customer = state- .store- .update_customer_by_global_id(- &customer_id,- customer,- updated_customer,- provider.get_key_store(),- provider.get_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update customer during `update_customer`")?;+ ) -> RouterResult<Option<domain::Customer>> {+ match (customer, updated_customer) {+ (Some(customer), Some(updated_customer)) => {+ let customer_id = customer.get_id().clone();++ state+ .store+ .update_customer_by_global_id(+ &customer_id,+ customer,+ updated_customer,+ provider.get_key_store(),+ provider.get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update customer during `update_customer`")+ .map(Some)+ }+ (customer, _) => Ok(customer),}- Ok(())}async fn run_decision_manager<'a>(diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex b37592d7c9..0226e36ac3 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -28,9 +28,7 @@ use hyperswitch_domain_models::{mandates::{self, ConnectorMandateReferenceId, MandateReferenceId},payments::payment_attempt::PaymentAttempt,};-use hyperswitch_masking::ExposeInterface;-#[cfg(feature = "v2")]-use hyperswitch_masking::PeekInterface;+use hyperswitch_masking::{ExposeInterface, PeekInterface};use router_derive;use router_env::{instrument, logger, tracing};use storage_impl::behaviour::Conversion;@@ -608,6 +606,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -637,6 +637,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorpayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1045,6 +1047,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu&'b self,state: &'b SessionState,processor: &domain::Processor,+ _provider: &domain::Provider,+ _customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1214,6 +1218,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,payment_data: PaymentData<F>,router_data: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,locale: &Option<String>,@@ -1231,6 +1237,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> forpayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1376,6 +1384,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSessionData>&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F, types::PaymentsSessionData, types::PaymentsResponseData>,locale: &Option<String>,@@ -1393,6 +1403,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSessionData>payment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1416,6 +1428,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpd&'b self,db: &'b SessionState,processor: &domain::Processor,+ _provider: &domain::Provider,+ _customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1541,6 +1555,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPostSessionTo&'b self,db: &'b SessionState,processor: &domain::Processor,+ _provider: &domain::Provider,+ _customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1603,6 +1619,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsUpdateMetadat&'b self,db: &'b SessionState,processor: &domain::Processor,+ _provider: &domain::Provider,+ _customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1692,6 +1710,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData>&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>,locale: &Option<String>,@@ -1709,6 +1729,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData>payment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1732,6 +1754,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPreAuthorizeC&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1753,6 +1777,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPreAuthorizeCpayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1774,6 +1800,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> f&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>,locale: &Option<String>,@@ -1791,6 +1819,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> fpayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1814,6 +1844,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCap&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1835,6 +1867,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCappayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1858,6 +1892,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCap&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1879,6 +1915,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCappayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1902,6 +1940,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsExtendAuthori&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -1923,6 +1963,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsExtendAuthoripayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1946,6 +1988,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsApproveData>&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F, types::PaymentsApproveData, types::PaymentsResponseData>,locale: &Option<String>,@@ -1963,6 +2007,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsApproveData>payment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -1984,6 +2030,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRejectData> f&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F, types::PaymentsRejectData, types::PaymentsResponseData>,locale: &Option<String>,@@ -2001,6 +2049,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRejectData> fpayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -2023,6 +2073,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,@@ -2049,6 +2101,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDapayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -2254,6 +2308,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData&'b self,db: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,payment_data: PaymentData<F>,response: types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,locale: &Option<String>,@@ -2271,6 +2327,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeDatapayment_data,response,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -2418,6 +2476,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(mut payment_data: PaymentData<F>,router_data: types::RouterData<F, T, types::PaymentsResponseData>,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,locale: &Option<String>,#[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connectors: Vec<RoutableConnectorChoice,@@ -3308,6 +3368,43 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(}}+ // Record the successful connector so later payments can prefer it.+ #[cfg(feature = "v1")]+ {+ if payment_attempt.status.is_success() {+ if let Some(((succeeded_connector, mca_id), (payment_method_type, customer))) =+ payment_attempt+ .connector+ .clone()+ .zip(payment_attempt.merchant_connector_id.as_ref())+ .zip(payment_attempt.payment_method_type.zip(customer))+ {+ // Store each profile independently so reroutes only replace that profile's preference.+ let profile_id = payment_attempt.profile_id.get_string_repr().to_string();+ let payment_method_type = payment_method_type.to_string();+ let preferred_connector =+ format!("{succeeded_connector}:{}", mca_id.get_string_repr());+ let key_store = provider.get_key_store();+ let storage_scheme = provider.get_account().storage_scheme;++ if let Err(error) = update_preferred_connectors(+ state,+ key_store,+ storage_scheme,+ customer,+ payment_method_type,+ profile_id,+ preferred_connector,+ )+ .await+ {+ metrics::PREFERRED_CONNECTORS_UPDATE_FAILURES.add(1, &[]);+ logger::error!(preferred_connectors_update_err = ?error);+ }+ }+ }+ }+payment_data.payment_intent = payment_intent;payment_data.payment_attempt = payment_attempt;payment_method_status.and_then(|status| {@@ -3911,6 +4008,113 @@ async fn create_or_update_payment_method_from_payment_response<F: Clone>(Ok(())}+/// Upserts one profile preference while preserving others, returning `None` when unchanged.+#[cfg(feature = "v1")]+pub(in crate::core::payments) fn upsert_profile_preference(+ existing: Option<&common_utils::pii::SecretSerdeValue>,+ payment_method_type: &str,+ profile_id: &str,+ preferred_connector: &str,+) -> Option<common_utils::pii::SecretSerdeValue> {+ const MAX_PROFILE_PREFERENCES: usize = 10;++ let original = existing.map(PeekInterface::peek);+ let mut preferences = original+ .and_then(|value| value.as_object())+ .cloned()+ .unwrap_or_default();++ let mut entries = Vec::with_capacity(MAX_PROFILE_PREFERENCES);+ let existing_entries = preferences+ .get(payment_method_type)+ .and_then(|value| value.as_array())+ .into_iter()+ .flatten();++ for entry in existing_entries {+ let Some(object) = entry.as_object() else {+ continue;+ };+ for (stored_profile_id, connector) in object {+ let Some(connector) = connector.as_str() else {+ continue;+ };+ if stored_profile_id == profile_id+ || entries+ .iter()+ .any(|entry: &serde_json::Value| entry.get(stored_profile_id).is_some())+ {+ continue;+ }+ entries.push(serde_json::json!({ stored_profile_id: connector }));+ if entries.len() == MAX_PROFILE_PREFERENCES - 1 {+ break;+ }+ }+ if entries.len() == MAX_PROFILE_PREFERENCES - 1 {+ break;+ }+ }++ entries.insert(0, serde_json::json!({ profile_id: preferred_connector }));++ preferences.insert(+ payment_method_type.to_string(),+ serde_json::Value::Array(entries),+ );++ let updated = serde_json::Value::Object(preferences);+ (original != Some(&updated)).then(|| common_utils::pii::SecretSerdeValue::new(updated))+}++/// Persist the connector behind a successful eligible payment on the customer row.+#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+async fn update_preferred_connectors(+ state: &SessionState,+ key_store: &domain::MerchantKeyStore,+ storage_scheme: enums::MerchantStorageScheme,+ customer: &domain::Customer,+ payment_method_type: String,+ profile_id: String,+ preferred_connector: String,+) -> RouterResult<()> {+ let is_payment_method_type_enabled =+ crate::core::payments::preferred_connectors_enabled_payment_method_types(state)+ .await+ .contains(&payment_method_type);++ if is_payment_method_type_enabled {+ let merchant_id = &customer.merchant_id;+ let customer_id = customer.get_id();+ if let Some(updated) = upsert_profile_preference(+ customer.preferred_connectors.as_ref(),+ &payment_method_type,+ &profile_id,+ &preferred_connector,+ ) {+ state+ .store+ .update_customer_by_customer_id_merchant_id(+ customer_id.to_owned(),+ merchant_id.to_owned(),+ customer.clone(),+ storage::CustomerUpdate::UpdatePreferredConnectors {+ preferred_connectors: Some(updated),+ last_modified_by: None,+ },+ key_store,+ storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update the customer's preferred connector")?;+ }+ }++ Ok(())+}+#[cfg(feature = "v2")]impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for &PaymentResponse {type Data = PaymentConfirmData<F>;@@ -4337,6 +4541,8 @@ impl&'b self,state: &'b SessionState,processor: &domain::Processor,+ provider: &domain::Provider,+ customer: Option<&domain::Customer>,payment_data: PaymentData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,router_data: types::RouterData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,@@ -4358,6 +4564,8 @@ implpayment_data,router_data,processor,+ provider,+ customer,locale,#[cfg(all(feature = "v1", feature = "dynamic_routing"))]routable_connector,@@ -4932,6 +5140,8 @@ impl<F: Clone + Send + Sync>&'b self,db: &'b SessionState,processor: &domain::Processor,+ _provider: &domain::Provider,+ _customer: Option<&domain::Customer>,mut payment_data: PaymentData<F>,router_data: types::RouterData<F,diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rsindex fba36b1d1f..f571758e19 100644--- a/crates/router/src/core/payments/retry.rs+++ b/crates/router/src/core/payments/retry.rs@@ -53,14 +53,17 @@ pub async fn do_gsm_actions<'a, F, ApiRequest, FData, D>(mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,platform: &domain::Platform,operation: &operations::BoxedOperation<'_, F, ApiRequest, D>,- customer: &Option<domain::Customer>,+ mut customer: Option<domain::Customer>,validate_result: &operations::ValidateResult,schedule_time: Option<time::PrimitiveDateTime>,frm_suggestion: Option<storage_enums::FrmSuggestion>,business_profile: &domain::Profile,feature_config: &core_utils::FeatureConfig,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,-) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>+) -> RouterResult<(+ types::RouterData<F, FData, types::PaymentsResponseData>,+ Option<domain::Customer>,+)>whereF: Clone + Send + Sync + std::fmt::Debug + 'static,FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,@@ -116,7 +119,7 @@ wherelet mut external_latency_total = router_data.external_latency;if should_step_up {- router_data = Box::pin(do_retry(+ (router_data, customer) = Box::pin(do_retry(&state.clone(),req_state.clone(),original_connector_data,@@ -225,7 +228,7 @@ where(connector_routing_data.connector_data, routing_decision)};- router_data = Box::pin(do_retry(+ (router_data, customer) = Box::pin(do_retry(&state.clone(),req_state.clone(),&connector,@@ -263,7 +266,7 @@ where// Report the whole payment's connector time, not just the last attempt's.router_data.external_latency = external_latency_total;- Ok(router_data)+ Ok((router_data, customer))}#[instrument(skip_all)]@@ -394,7 +397,7 @@ pub async fn do_retry<'a, F, ApiRequest, FData, D>(req_state: ReqState,connector: &'a api::ConnectorData,operation: &'a operations::BoxedOperation<'a, F, ApiRequest, D>,- customer: &'a Option<domain::Customer>,+ customer: Option<domain::Customer>,platform: &domain::Platform,payment_data: &'a mut D,router_data: types::RouterData<F, FData, types::PaymentsResponseData>,@@ -407,7 +410,10 @@ pub async fn do_retry<'a, F, ApiRequest, FData, D>(routing_decision: Option<routing_helpers::RoutingDecisionData>,initial_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>,feature_config: &core_utils::FeatureConfig,-) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>+) -> RouterResult<(+ types::RouterData<F, FData, types::PaymentsResponseData>,+ Option<domain::Customer>,+)>whereF: Clone + Send + Sync + std::fmt::Debug + 'static,FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,@@ -458,7 +464,7 @@ where.as_ref().and_then(|customer| customer.connector_customer.as_ref());- let (updated_customer, call_connector_service_response, updated_state) =+ let (customer_update, call_connector_service_response, updated_state) =payments::decide_unified_connector_service_call(state,platform.get_processor(),@@ -479,14 +485,13 @@ wheretokenization_action,).await?;- // Update customer at provider level after connector operations complete- operation+ let customer = operation.to_domain()?.update_customer(&updated_state,platform.get_provider(),- customer.clone(),- updated_customer,+ customer,+ customer_update,).await?;@@ -507,7 +512,7 @@ where&dimensions,).await?;- Ok(router_data)+ Ok((router_data, customer))}#[cfg(feature = "v2")]diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 4785661ba2..76f0aa8893 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -1,4 +1,6 @@use hyperswitch_domain_models::mandates;+#[cfg(all(test, feature = "v1"))]+mod tests;mod transformers;pub mod utils;#[cfg(all(feature = "v1", feature = "dynamic_routing"))]@@ -1570,6 +1572,7 @@ pub struct HybridRoutingInput<'a> {pub fallback_config: &'a [routing_types::RoutableConnectorChoice],pub static_connectors: &'a [routing_types::RoutableConnectorChoice],pub static_approach: common_enums::RoutingApproach,+ pub preferred_connector: Option<String>,}#[cfg(feature = "v1")]@@ -1577,6 +1580,26 @@ pub struct HybridRoutingStage;#[cfg(feature = "v1")]impl HybridRoutingStage {+ #[cfg(any(feature = "dynamic_routing", test))]+ fn resolve_preferred_connector(+ preferred: &str,+ static_connectors: &[routing_types::RoutableConnectorChoice],+ ) -> Option<String> {+ let preferred_connector_name = preferred.split_once(':').map(|(name, _)| name)?;+ static_connectors+ .iter()+ .find(|choice| choice.to_string() == preferred)+ .or_else(|| {+ static_connectors.iter().find(|choice| {+ choice+ .connector+ .to_string()+ .eq_ignore_ascii_case(preferred_connector_name)+ })+ })+ .map(ToString::to_string)+ }+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]fn build_dynamic_routing_request(&self,@@ -1588,10 +1611,16 @@ impl HybridRoutingStage {.open_router.dynamic_routing_enabled.then(|| {+ // Match an exact account first, then any eligible account for the same connector.+ let preferred_connector = input.preferred_connector.as_deref().and_then(|value| {+ Self::resolve_preferred_connector(value, input.static_connectors)+ });+OpenRouterDecideGatewayRequest::construct_sr_request(input.payment_dsl_input.payment_attempt,input.static_connectors.to_vec(),Some(or_types::RankingAlgorithm::SrBasedRouting),+ preferred_connector,)})}@@ -1704,11 +1733,22 @@ pub async fn perform_hybrid_routing_if_enabled(fallback_config: &[routing_types::RoutableConnectorChoice],static_connectors: &[routing_types::RoutableConnectorChoice],static_approach: common_enums::RoutingApproach,+ preferred_connector: Option<String>,) -> (Vec<routing_types::RoutableConnectorChoice>,common_enums::RoutingApproach,) {let stage = HybridRoutingStage;++ let preferred_connector = match preferred_connector {+ Some(connector)+ if utils::is_preferred_connectors_routing_enabled(state, dimensions).await =>+ {+ Some(connector)+ }+ _ => None,+ };+let input = HybridRoutingInput {state,business_profile,@@ -1717,6 +1757,7 @@ pub async fn perform_hybrid_routing_if_enabled(fallback_config,static_connectors,static_approach: static_approach.clone(),+ preferred_connector,};// Flag-aware like every other consumer: with static_routing_enabled off the profile is@@ -3681,6 +3722,8 @@ pub async fn perform_decide_gateway_call_with_open_router(payment_attempt,routable_connectors.clone(),Some(or_types::RankingAlgorithm::SrBasedRouting),+ // Legacy routing does not send preferred connectors.+ None,);let routing_events_wrapper = utils::RoutingEventsWrapper::new(diff --git a/crates/router/src/core/payments/routing/tests.rs b/crates/router/src/core/payments/routing/tests.rsnew file mode 100644index 0000000000..ed76aae47d--- /dev/null+++ b/crates/router/src/core/payments/routing/tests.rs@@ -0,0 +1 @@+mod preferred_connectors;diff --git a/crates/router/src/core/payments/routing/tests/preferred_connectors.rs b/crates/router/src/core/payments/routing/tests/preferred_connectors.rsnew file mode 100644index 0000000000..46b8e7c4d7--- /dev/null+++ b/crates/router/src/core/payments/routing/tests/preferred_connectors.rs@@ -0,0 +1,187 @@+use api_models::routing::{RoutableChoiceKind, RoutableConnectorChoice};+use common_utils::{id_type, pii::SecretSerdeValue};+use euclid::enums::RoutableConnectors;+use hyperswitch_masking::PeekInterface;+use serde_json::json;++use super::super::HybridRoutingStage;+use crate::core::payments::{+ operations::payment_response::upsert_profile_preference, preferred_connector_for_profile,+};++fn connector_choice(+ connector: RoutableConnectors,+ mca_id: &str,+) -> Option<RoutableConnectorChoice> {+ id_type::MerchantConnectorAccountId::wrap(mca_id.to_string())+ .ok()+ .map(|merchant_connector_id| RoutableConnectorChoice {+ choice_kind: RoutableChoiceKind::FullStruct,+ connector,+ merchant_connector_id: Some(merchant_connector_id),+ })+}++#[test]+fn preference_updates_preserve_other_profiles_and_payment_method_types() {+ let existing = SecretSerdeValue::new(json!({+ "interac": [{"pro_one": "loonio:mca_old"}, {"pro_two": "payper:mca_two"}],+ "ideal": [{"pro_one": "adyen:mca_three"}]+ }));+ let updated =+ upsert_profile_preference(Some(&existing), "interac", "pro_one", "loonio:mca_new")+ .expect("changed account must update the preference");+ assert_eq!(+ updated.peek(),+ &json!({+ "interac": [{"pro_one": "loonio:mca_new"}, {"pro_two": "payper:mca_two"}],+ "ideal": [{"pro_one": "adyen:mca_three"}]+ })+ );+ assert_eq!(+ preferred_connector_for_profile(updated.peek(), "interac", "pro_one").as_deref(),+ Some("loonio:mca_new")+ );+ assert_eq!(+ preferred_connector_for_profile(updated.peek(), "interac", "pro_two").as_deref(),+ Some("payper:mca_two")+ );+ assert_eq!(+ preferred_connector_for_profile(updated.peek(), "ideal", "pro_one").as_deref(),+ Some("adyen:mca_three")+ );+ assert_eq!(+ preferred_connector_for_profile(updated.peek(), "interac", "pro_missing"),+ None+ );+ assert_eq!(+ preferred_connector_for_profile(updated.peek(), "card", "pro_one"),+ None+ );+ assert_eq!(+ upsert_profile_preference(Some(&updated), "interac", "pro_one", "loonio:mca_new"),+ None+ );+}++#[test]+fn preference_history_is_bounded_and_newest_profile_is_first() {+ let mut value = None;+ for index in 0..11 {+ value = upsert_profile_preference(+ value.as_ref(),+ "interac",+ &format!("pro_{index}"),+ "loonio:mca_one",+ );+ }+ let value = value.expect("preferences were recorded");+ let preferences = value+ .peek()+ .get("interac")+ .and_then(|entry| entry.as_array())+ .expect("profile list");+ assert_eq!(preferences.len(), 10);+ assert_eq!(+ preferences.first(),+ Some(&json!({"pro_10": "loonio:mca_one"}))+ );+ assert_eq!(+ preferred_connector_for_profile(value.peek(), "interac", "pro_0"),+ None+ );+}++#[test]+fn repeated_success_refreshes_profile_recency_before_eviction() {+ let mut value = None;+ for index in 0..10 {+ value = upsert_profile_preference(+ value.as_ref(),+ "interac",+ &format!("pro_{index}"),+ "loonio:mca_one",+ );+ }+ let value = upsert_profile_preference(value.as_ref(), "interac", "pro_0", "loonio:mca_one")+ .expect("a repeated success refreshes an old profile");+ let value = upsert_profile_preference(Some(&value), "interac", "pro_10", "loonio:mca_one")+ .expect("a new profile is recorded");++ assert_eq!(+ preferred_connector_for_profile(value.peek(), "interac", "pro_0").as_deref(),+ Some("loonio:mca_one")+ );+ assert_eq!(+ preferred_connector_for_profile(value.peek(), "interac", "pro_1"),+ None+ );+}++#[test]+fn malformed_preferences_are_ignored_and_repaired_on_success() {+ for existing in [+ json!(null),+ json!("invalid"),+ json!({"interac": false}),+ json!({"interac": [null, {"pro_one": 42}]}),+ ] {+ assert_eq!(+ preferred_connector_for_profile(&existing, "interac", "pro_one"),+ None+ );+ let existing = SecretSerdeValue::new(existing);+ let updated =+ upsert_profile_preference(Some(&existing), "interac", "pro_one", "loonio:mca_one")+ .expect("replace invalid preference");+ assert_eq!(+ preferred_connector_for_profile(updated.peek(), "interac", "pro_one").as_deref(),+ Some("loonio:mca_one")+ );+ }+}++#[test]+fn malformed_and_duplicate_profile_entries_are_canonicalized() {+ let existing = SecretSerdeValue::new(json!({+ "interac": [+ null,+ {"pro_one": "loonio:mca_old", "pro_two": "payper:mca_two"},+ {"pro_one": "loonio:mca_new"},+ {"pro_invalid": 42}+ ],+ "ideal": [{"pro_one": "adyen:mca_three"}]+ }));+ let updated =+ upsert_profile_preference(Some(&existing), "interac", "pro_one", "loonio:mca_new")+ .expect("duplicates and malformed entries require canonicalization");++ assert_eq!(+ updated.peek(),+ &json!({+ "interac": [+ {"pro_one": "loonio:mca_new"},+ {"pro_two": "payper:mca_two"}+ ],+ "ideal": [{"pro_one": "adyen:mca_three"}]+ })+ );+}++#[test]+fn exact_preferred_account_match_keeps_mca_id_case_sensitive() {+ let connectors = [+ connector_choice(RoutableConnectors::Stripe, "mca_CaseSensitive"),+ connector_choice(RoutableConnectors::Stripe, "mca_casesensitive"),+ ]+ .into_iter()+ .flatten()+ .collect::<Vec<_>>();+ assert_eq!(connectors.len(), 2);++ assert_eq!(+ HybridRoutingStage::resolve_preferred_connector("stripe:mca_casesensitive", &connectors,)+ .as_deref(),+ Some("stripe:mca_casesensitive")+ );+}diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rsindex 48d4955bf8..3964453657 100644--- a/crates/router/src/core/payments/routing/utils.rs+++ b/crates/router/src/core/payments/routing/utils.rs@@ -2293,6 +2293,20 @@ pub async fn get_routing_result_source(.await}+/// Checks whether preferred-connector routing is enabled for this profile.+pub async fn is_preferred_connectors_routing_enabled(+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+) -> bool {+ dimensions+ .get_preferred_connectors_routing_enabled(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await+}+/// 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,diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex fa6186203b..0b8704e98d 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -288,14 +288,14 @@ pub async fn make_connector_decision(api::ConnectorCallType::PreDetermined(routing_data) => {let frm_outcome = match payout_frm_applicability {Some(applicability) => handle_payout_pre_frm_result!(- fraud_check::pre_payouts_frm_core(+ Box::pin(fraud_check::pre_payouts_frm_core(state,platform,payout_data,&routing_data.connector_data,applicability,&pre_frm_failure_mode,- )+ )).await,&pre_frm_failure_mode,platform,@@ -341,14 +341,14 @@ pub async fn make_connector_decision(let frm_outcome = match payout_frm_applicability {Some(applicability) => handle_payout_pre_frm_result!(- fraud_check::pre_payouts_frm_core(+ Box::pin(fraud_check::pre_payouts_frm_core(state,platform,payout_data,&connector_data,applicability,&pre_frm_failure_mode,- )+ )).await,&pre_frm_failure_mode,platform,diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rsindex 0e3128567d..2edd518f77 100644--- a/crates/router/src/core/routing/transformers.rs+++ b/crates/router/src/core/routing/transformers.rs@@ -125,6 +125,7 @@ pub trait OpenRouterDecideGatewayRequestExt {attempt: &PaymentAttempt,eligible_gateway_list: Vec<RoutableConnectorChoice>,ranking_algorithm: Option<RankingAlgorithm>,+ preferred_connector: Option<String>,) -> SelfwhereSelf: Sized;@@ -145,6 +146,7 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {attempt: &PaymentAttempt,eligible_gateway_list: Vec<RoutableConnectorChoice>,ranking_algorithm: Option<RankingAlgorithm>,+ preferred_connector: Option<String>,) -> Self {Self {payment_info: PaymentInfo {@@ -156,6 +158,7 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {payment_method: attempt.payment_method.unwrap_or_default(),metadata: None,card_isin: None,+ preferred_connectors: preferred_connector.map(|entry| vec![entry]),},merchant_id: attempt.profile_id.clone(),eligible_gateway_list: Some(@@ -184,6 +187,7 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {metadata,payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attemptpayment_method: attempt.payment_method.unwrap_or_default(),+ preferred_connectors: None,},merchant_id: attempt.profile_id.clone(),// eligible gateway list is not used in debit routingdiff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex 40ab427a66..bdd0aef642 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -9,6 +9,7 @@ global_meter!(GLOBAL_METER, "ROUTER_API");counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hitscounter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses+counter_metric!(PREFERRED_CONNECTORS_UPDATE_FAILURES, GLOBAL_METER);// API Level Metricscounter_metric!(REQUESTS_RECEIVED, GLOBAL_METER);diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rsindex 7069c9a766..4192eee615 100644--- a/crates/storage_impl/src/customers.rs+++ b/crates/storage_impl/src/customers.rs@@ -1325,6 +1325,7 @@ impl Conversion for domain::Customer {.last_modified_by.map(|last_modified_by| last_modified_by.to_string()),id: global_customer_id,+ preferred_connectors: self.preferred_connectors,})}@@ -1408,6 +1409,7 @@ impl Conversion for domain::Customer {last_modified_by: item.last_modified_by.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ preferred_connectors: item.preferred_connectors,})}@@ -1438,6 +1440,7 @@ impl Conversion for domain::Customer {.as_ref().map(|created_by| created_by.to_string()),last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creation+ preferred_connectors: self.preferred_connectors,})}}@@ -1473,6 +1476,7 @@ impl ForeignFrom<domain::CustomerUpdate> for diesel_models::CustomerUpdateInterntax_registration_id: tax_registration_id.map(Encryption::from),document_details: document_details.map(Encryption::from),last_modified_by,+ preferred_connectors: None,},domain::CustomerUpdate::ConnectorCustomer {connector_customer,@@ -1492,6 +1496,7 @@ impl ForeignFrom<domain::CustomerUpdate> for diesel_models::CustomerUpdateInterntax_registration_id: None,document_details: None,last_modified_by,+ preferred_connectors: None,},domain::CustomerUpdate::UpdateDefaultPaymentMethod {default_payment_method_id,@@ -1511,6 +1516,27 @@ impl ForeignFrom<domain::CustomerUpdate> for diesel_models::CustomerUpdateInterntax_registration_id: None,document_details: None,last_modified_by,+ preferred_connectors: None,+ },+ domain::CustomerUpdate::UpdatePreferredConnectors {+ preferred_connectors,+ last_modified_by,+ } => Self {+ preferred_connectors,+ modified_at: date_time::now(),+ name: None,+ email: None,+ phone: None,+ description: None,+ phone_country_code: None,+ metadata: None,+ connector_customer: None,+ default_payment_method_id: None,+ updated_by: None,+ address_id: None,+ tax_registration_id: None,+ document_details: None,+ last_modified_by,},}}@@ -1548,6 +1574,7 @@ impl Conversion for domain::Customer {last_modified_by: self.last_modified_by.map(|last_modified_by| last_modified_by.to_string()),+ preferred_connectors: self.preferred_connectors,})}@@ -1671,6 +1698,7 @@ impl Conversion for domain::Customer {last_modified_by: item.last_modified_by.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ preferred_connectors: item.preferred_connectors,})}@@ -1703,6 +1731,7 @@ impl Conversion for domain::Customer {.map(|created_by| created_by.to_string()),last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creationcustomer_id: Some(self.id),+ preferred_connectors: self.preferred_connectors,})}}diff --git a/migrations/2026-09-23-100001_add_preferred_connectors_to_customers/down.sql b/migrations/2026-09-23-100001_add_preferred_connectors_to_customers/down.sqlnew file mode 100644index 0000000000..b78dd73fe3--- /dev/null+++ b/migrations/2026-09-23-100001_add_preferred_connectors_to_customers/down.sql@@ -0,0 +1 @@+ALTER TABLE customers DROP COLUMN IF EXISTS preferred_connectors;diff --git a/migrations/2026-09-23-100001_add_preferred_connectors_to_customers/up.sql b/migrations/2026-09-23-100001_add_preferred_connectors_to_customers/up.sqlnew file mode 100644index 0000000000..bc675625d9--- /dev/null+++ b/migrations/2026-09-23-100001_add_preferred_connectors_to_customers/up.sql@@ -0,0 +1 @@+ALTER TABLE customers ADD COLUMN IF NOT EXISTS preferred_connectors JSONB;