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(ucs): add org-level rollout config with precedence hierarchy (#12057)
Amitsingh Tanwara828fb20f862
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 9cbee34053..a7c5b0a0b2 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -338,6 +338,10 @@ pub const PSD2_COUNTRIES: [Country; 27] = [// Rollout percentage config prefixpub const UCS_ROLLOUT_PERCENT_CONFIG_PREFIX: &str = "ucs_rollout_config";+// Sentinel value cached when a rollout config key is absent, so subsequent lookups+// skip the DB entirely instead of hitting it on every cache miss.+pub const UCS_ROLLOUT_CONFIG_NOT_CONFIGURED: &str = "not_configured";+// UCS feature enabled configpub const UCS_ENABLED: &str = "ucs_enabled";diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 63c460417e..c2b23802d6 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2651,6 +2651,65 @@ pub async fn should_execute_based_on_rollout(}}+/// Tries rollout config keys from highest to lowest precedence, returns the result+/// for the first key found in the config table. Falls back to default if none found.+///+/// Key precedence (highest → lowest):+/// 1. `ucs_rollout_config_<merchant_id>_<connector>_...` — merchant + connector+/// 2. `ucs_rollout_config_<org_id>_<merchant_id>_<connector>_...` — org + merchant + connector+/// 3. `ucs_rollout_config_<org_id>_<merchant_id>` — org + merchant+/// 4. `ucs_rollout_config_<org_id>` — org level+///+/// Uses `find_config_by_key_unwrap_or` with a sentinel so absent keys are cached after+/// the first DB miss — subsequent requests hit in-memory cache instead of the DB.+/// The future is boxed (`Box::pin`) to keep stack frames small under high concurrency.+pub async fn should_execute_based_on_rollout_with_precedence(+ state: &SessionState,+ // Keys in ascending precedence order (lowest first, highest last)+ keys: &[String],+) -> RouterResult<RolloutExecutionResult> {+ // Iterate highest → lowest (reverse of the input order)+ for key in keys.iter().rev() {+ // Box the future to avoid large stack frames from nested async in debug builds+ let result = Box::pin(state.store.find_config_by_key_unwrap_or(+ key,+ Some(consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED.to_string()),+ ))+ .await+ .ok();++ match result {+ Some(config) if config.config == consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED => {+ // Sentinel — key absent in DB, cached to skip future DB calls+ logger::debug!(config_key = %key, "Rollout config not set, trying next key");+ continue;+ }+ Some(config) => {+ logger::info!(config_key = %key, "Rollout config found, using this key");+ return Ok(serde_json::from_str::<RolloutConfig>(&config.config)+ .map(RolloutExecutionResult::from)+ .map_err(|err| {+ logger::error!(+ error = ?err,+ config = %config.config,+ "Failed to parse rollout config as JSON. Defaulting to not execute."+ );+ RolloutExecutionResult::default()+ })+ .unwrap_or_default());+ }+ None => {+ // Unexpected DB error — skip and try next key+ continue;+ }+ }+ }++ // No key found at any level — caller will apply default execution mode+ logger::debug!("No rollout config found at any precedence level, using default execution mode");+ Ok(RolloutExecutionResult::default())+}+pub fn determine_standard_vault_action(is_network_tokenization_enabled: bool,mandate_id: Option<mandates::MandateIds>,diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 46eeef3711..ab9cc9d2b8 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -46,7 +46,8 @@ use crate::{errors::{self, RouterResult},payments::{helpers::{- is_ucs_enabled, should_execute_based_on_rollout, MerchantConnectorAccountType,+ is_ucs_enabled, should_execute_based_on_rollout,+ should_execute_based_on_rollout_with_precedence, MerchantConnectorAccountType,ProxyOverride,},OperationSessionGetters, OperationSessionSetters,@@ -303,6 +304,7 @@ where{// Extract context informationlet merchant_id = processor.get_account().get_id().get_string_repr();+ let org_id = processor.get_account().get_org_id().get_string_repr();let connector_name = &router_data.connector;let connector_enum = Connector::from_str(connector_name)@@ -314,9 +316,12 @@ where// Check UCS availability using idiomatic helperlet ucs_availability = check_ucs_availability(state).await;- let rollout_key = match transaction_type {+ // Build rollout keys in ascending precedence order.+ // Payments use org-level hierarchy; payouts use a single merchant-level key for now.+ let rollout_keys = match transaction_type {common_enums::TransactionType::Payment| common_enums::TransactionType::ThreeDsAuthentication => build_rollout_keys(+ org_id,merchant_id,connector_name,&flow_name,@@ -335,8 +340,9 @@ wherelet connector_integration_type =determine_connector_integration_type(state, connector_enum).await?;- // Check rollout key availability and shadow key presence (optimized to reduce DB calls)- let rollout_result = should_execute_based_on_rollout(state, &rollout_key).await?;+ // Try keys highest → lowest precedence, use first match found+ let rollout_result =+ should_execute_based_on_rollout_with_precedence(state, &rollout_keys).await?;// Single decision point using pattern matchinglet (gateway_system, mut execution_path) = if ucs_availability == UcsAvailability::Disabled {@@ -525,25 +531,35 @@ fn decide_execution_path(}}-/// Build rollout keys based on flow type - include payment method for payments, skip for refunds+/// Builds rollout config keys in ascending precedence order:+/// 1. `ucs_rollout_config_<org_id>` — org level (lowest)+/// 2. `ucs_rollout_config_<org_id>_<merchant_id>` — org + merchant+/// 3. `ucs_rollout_config_<org_id>_<merchant_id>_<connector>_...` — org + merchant + connector (highest)+///+/// The caller tries keys highest → lowest and uses the first match found.+/// Builds rollout config keys in ascending precedence order (lowest → highest):+/// 1. `ucs_rollout_config_<org_id>` — org level+/// 2. `ucs_rollout_config_<org_id>_<merchant_id>` — org + merchant+/// 3. `ucs_rollout_config_<org_id>_<merchant_id>_<connector>_...` — org + merchant + connector+/// 4. `ucs_rollout_config_<merchant_id>_<connector>_...` — merchant + connector (highest)+///+/// The caller iterates highest → lowest and uses the first match found.fn build_rollout_keys(+ org_id: &str,merchant_id: &str,connector_name: &str,flow_name: &str,payment_method: common_enums::PaymentMethod,payment_method_type: Option<PaymentMethodType>,-) -> String {- // Detect if this is a refund flow based on flow name+) -> Vec<String> {+ let prefix = consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX;let is_refund_flow = matches!(flow_name, "Execute" | "RSync");- if is_refund_flow {- // Refund flows: UCS_merchant_connector_flow (e.g., UCS_merchant123_stripe_Execute)- format!(- "{}_{}_{}_{}",- consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,- merchant_id,- connector_name,- flow_name+ let (merchant_connector_key, org_merchant_connector_key) = if is_refund_flow {+ // Refund flows: ucs_rollout_config_<merchant_id>_<connector>_<flow>+ (+ format!("{prefix}_{merchant_id}_{connector_name}_{flow_name}"),+ format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{flow_name}"),)} else {match payment_method {@@ -555,14 +571,9 @@ fn build_rollout_keys(let payment_method_type_str = payment_method_type.map(|pmt| pmt.to_string()).unwrap_or_else(|| "unknown".to_string());- format!(- "{}_{}_{}_{}_{}_{}",- consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,- merchant_id,- connector_name,- payment_method_str,- payment_method_type_str,- flow_name+ (+ format!("{prefix}_{merchant_id}_{connector_name}_{payment_method_str}_{payment_method_type_str}_{flow_name}"),+ format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{payment_method_str}_{payment_method_type_str}_{flow_name}"),)}common_enums::PaymentMethod::Card@@ -579,38 +590,42 @@ fn build_rollout_keys(| common_enums::PaymentMethod::OpenBanking => {// For other payment methods, use a generic format without specific payment method type detailslet payment_method_str = payment_method.to_string();- format!(- "{}_{}_{}_{}_{}",- consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,- merchant_id,- connector_name,- payment_method_str,- flow_name+ (+ format!("{prefix}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),+ format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),)}}- }+ };++ // Ascending precedence order (lowest first, highest last)+ vec![+ format!("{prefix}_{org_id}"),+ format!("{prefix}_{org_id}_{merchant_id}"),+ org_merchant_connector_key,+ merchant_connector_key,+ ]}-/// Build rollout keys based on flow type - include payment method type for payouts+/// Build rollout key for payouts — single key, org-level precedence not applied to payouts yet.fn build_rollout_keys_for_payouts(merchant_id: &str,connector_name: &str,flow_name: &str,payment_method_type: Option<PaymentMethodType>,-) -> String {- let payment_method_type_str = payment_method_type- .map(|data| data.to_string())+) -> Vec<String> {+ let pmt = payment_method_type+ .map(|t| t.to_string()).unwrap_or_else(|| "unknown".to_string());- format!(+ vec![format!("{}_{}_{}_{}_{}",consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,merchant_id,connector_name,- payment_method_type_str,+ pmt,flow_name- )+ )]}/// Extracts the gateway system from the payment intent's feature metadata@@ -704,7 +719,6 @@ pub async fn should_call_unified_connector_service_for_webhooks(.map(|id| id.get_string_repr().to_owned()).unwrap_or_else(|| connector_name.to_string());- // Build rollout keys - webhooks don't use payment method, so use a simplified key formatlet rollout_key = format!("{}_{}_{}_{}",consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,@@ -720,7 +734,6 @@ pub async fn should_call_unified_connector_service_for_webhooks(// For webhooks, there is no previous gateway system to consider (webhooks are stateless)let previous_gateway = None;- // Check both rollout keys to determine priority based on shadow percentagelet rollout_result = should_execute_based_on_rollout(state, &rollout_key).await?;// Use the same decision logic as payments, with no call_connector_action to consider