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 automatic kill switch for deterministic UCS failures (#13639)
gopikrishna0009cb2e6e83e79
diff --git a/crates/hyperswitch_interfaces/src/api/gateway.rs b/crates/hyperswitch_interfaces/src/api/gateway.rsindex 331ebf1368..c4abcf2087 100644--- a/crates/hyperswitch_interfaces/src/api/gateway.rs+++ b/crates/hyperswitch_interfaces/src/api/gateway.rs@@ -410,6 +410,9 @@ wherelet return_raw_connector_response_clone = return_raw_connector_response;let context_clone = context;let connector_name = router_data.connector.clone();+ let merchant_id = router_data.merchant_id.clone();+ let payment_method = router_data.payment_method;+ let payment_method_type = router_data.payment_method_type;tokio::spawn(async move {let gateway: Box<@@ -442,6 +445,9 @@ whereconnector_name,direct_for_compare,ucs_for_compare,+ Some(&merchant_id),+ Some(payment_method),+ payment_method_type,).await;}@@ -544,6 +550,9 @@ wherelet return_raw_connector_response_clone = return_raw_connector_response;let context_clone = context;let connector_name = router_data.connector.clone();+ let merchant_id = router_data.merchant_id.clone();+ let payment_method = router_data.payment_method;+ let payment_method_type = router_data.payment_method_type;tokio::spawn(async move {let gateway: Box<@@ -576,6 +585,9 @@ whereconnector_name,direct_for_compare,ucs_for_compare,+ Some(&merchant_id),+ Some(payment_method),+ payment_method_type,).await;}diff --git a/crates/hyperswitch_interfaces/src/helpers.rs b/crates/hyperswitch_interfaces/src/helpers.rsindex f7a6550c9a..cd07ccad18 100644--- a/crates/hyperswitch_interfaces/src/helpers.rs+++ b/crates/hyperswitch_interfaces/src/helpers.rs@@ -1,8 +1,8 @@use common_utils::{- consts::{X_CONNECTOR_NAME, X_SUB_FLOW_NAME},+ consts::{X_CONNECTOR_NAME, X_PAYMENT_METHOD, X_PAYMENT_METHOD_TYPE, X_SUB_FLOW_NAME},errors as common_utils_errors,ext_traits::Encode,- request,+ id_type, request,};use error_stack::ResultExt;use hyperswitch_domain_models::router_data;@@ -52,6 +52,9 @@ pub async fn serialize_comparison_results_and_send<S, F, RouterDReq, RouterDResprouter_data::RouterData<F, RouterDReq, RouterDResp>,String,>,+ merchant_id: Option<&id_type::MerchantId>,+ payment_method: Option<common_enums::enums::PaymentMethod>,+ payment_method_type: Option<common_enums::enums::PaymentMethodType>,) whereS: api_client::ApiClientWrapper + GetComparisonServiceConfig,F: Send + Clone + Sync + 'static,@@ -94,6 +97,9 @@ pub async fn serialize_comparison_results_and_send<S, F, RouterDReq, RouterDRespconnector_name,sub_flow_name,request_id,+ merchant_id,+ payment_method,+ payment_method_type,).await.inspect_err(|e| logger::warn!("Failed to send comparison data: {:?}", e));@@ -107,6 +113,7 @@ pub async fn serialize_webhook_outcome_and_send_to_comparison_service<P, S>(comparison_service_config: types::ComparisonServiceConfig,connector_name: String,request_id: Option<String>,+ merchant_id: Option<&id_type::MerchantId>,) whereP: serde::Serialize + std::fmt::Debug,S: serde::Serialize + std::fmt::Debug,@@ -132,6 +139,9 @@ pub async fn serialize_webhook_outcome_and_send_to_comparison_service<P, S>(connector_name,Some("webhook".to_string()),request_id,+ merchant_id,+ None,+ None,).await{@@ -140,6 +150,7 @@ pub async fn serialize_webhook_outcome_and_send_to_comparison_service<P, S>(}/// Sends router data comparison to external service+#[allow(clippy::too_many_arguments)]pub async fn send_comparison_data(state: &dyn api_client::ApiClientWrapper,comparison_data: ComparisonData,@@ -147,6 +158,9 @@ pub async fn send_comparison_data(connector_name: String,sub_flow_name: Option<String>,request_id: Option<String>,+ merchant_id: Option<&id_type::MerchantId>,+ payment_method: Option<common_enums::enums::PaymentMethod>,+ payment_method_type: Option<common_enums::enums::PaymentMethodType>,) -> common_utils_errors::CustomResult<(), errors::HttpClientError> {let mut request = request::RequestBuilder::new().method(request::Method::Post)@@ -175,6 +189,27 @@ pub async fn send_comparison_data();}+ if let Some(merchant_id) = merchant_id {+ request.add_header(+ common_utils::consts::X_MERCHANT_ID,+ hyperswitch_masking::Maskable::Normal(merchant_id.get_string_repr().to_string()),+ );+ }++ if let Some(pm) = payment_method {+ request.add_header(+ X_PAYMENT_METHOD,+ hyperswitch_masking::Maskable::Normal(pm.to_string()),+ );+ }++ if let Some(pmt) = payment_method_type {+ request.add_header(+ X_PAYMENT_METHOD_TYPE,+ hyperswitch_masking::Maskable::Normal(pmt.to_string()),+ );+ }+let _ = state.get_api_client().send_request(diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 9773f1bda5..d9a7740282 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -1398,3 +1398,207 @@ impl ErrorSwitch<ConnectorError> for UnifiedConnectorServiceError {}}}++/// Why a UCS failure should return a rollout scope to the direct connector integration.+///+/// Named by where the failure originated, because that decides who fixes it: a `Hyperswitch`+/// reason is a bug in this repo's request or response mapping, a `Ucs` reason is not.+///+/// Doubles as the metric label, so it is a small fixed set rather than the error itself — the+/// error carries free-form strings and would be unbounded label cardinality.+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display)]+#[strum(serialize_all = "snake_case")]+pub enum UcsKillSwitchReason {+ /// Hyperswitch could not build a valid request. UCS was never reached.+ HyperswitchRequestInvalid,+ /// Hyperswitch could not decode what UCS returned. The two models disagree.+ HyperswitchResponseUndecodable,+ /// UCS rejected the request Hyperswitch sent it.+ UcsRejectedRequest,+ /// UCS does not implement this flow for this connector.+ UcsFlowUnsupported,+ /// UCS failed internally, or failed the flow without saying more.+ UcsInternalError,+ /// UCS could not be reached, or was too unwell to answer.+ UcsUnreachable,+ /// The connector rejected the request. May be a legitimate decline or a request UCS built+ /// wrongly — indistinguishable at this layer, so we trip conservatively because falling back+ /// to the battle-tested direct path is always safe.+ ConnectorOutcome,+}++impl UnifiedConnectorServiceError {+ /// Whether this failure should return the rollout scope to the direct connector integration.+ ///+ /// Every error qualifies, including [`Self::ConnectorError`]. A connector rejection may be a+ /// legitimate decline or a request UCS built wrongly — since the two are indistinguishable,+ /// we trip conservatively: falling back to the battle-tested direct path is always safe.+ ///+ /// Exhaustive: a new variant must be classified here rather than defaulting.+ pub fn ucs_kill_switch_reason(&self) -> Option<UcsKillSwitchReason> {+ match self {+ // Hyperswitch could not read UCS's answer.+ Self::ResponseDeserializationFailed | Self::ParsingFailed => {+ Some(UcsKillSwitchReason::HyperswitchResponseUndecodable)+ }++ // Hyperswitch could not build the request. UCS was never reached.+ Self::RequestEncodingFailed+ | Self::RequestEncodingFailedWithReason(_)+ | Self::MissingRequiredField { .. }+ | Self::MissingRequiredFields { .. }+ | Self::MissingConnectorName+ | Self::InvalidConnectorName+ | Self::InvalidDataFormat { .. }+ | Self::FailedToObtainAuthType+ | Self::HeaderInjectionFailed(_) => {+ Some(UcsKillSwitchReason::HyperswitchRequestInvalid)+ }++ // Raised by Hyperswitch, but it reports a flow UCS cannot serve.+ Self::NotImplemented(_) => Some(UcsKillSwitchReason::UcsFlowUnsupported),++ // UCS-side by construction: `from_grpc_error` extracts connector errors first.+ Self::TonicStatus { code, .. } => match code {+ // UCS-wide rather than scope-specific. Still worth falling back for: while UCS+ // is unwell the payment has nowhere else to go and fails outright.+ tonic::Code::Unavailable+ | tonic::Code::DeadlineExceeded+ | tonic::Code::ResourceExhausted+ | tonic::Code::Aborted+ | tonic::Code::Cancelled => Some(UcsKillSwitchReason::UcsUnreachable),++ // UCS rejected what Hyperswitch sent it.+ tonic::Code::InvalidArgument+ | tonic::Code::FailedPrecondition+ | tonic::Code::OutOfRange+ | tonic::Code::NotFound+ | tonic::Code::AlreadyExists+ | tonic::Code::Unauthenticated+ | tonic::Code::PermissionDenied => Some(UcsKillSwitchReason::UcsRejectedRequest),++ tonic::Code::Unimplemented => Some(UcsKillSwitchReason::UcsFlowUnsupported),++ // UCS itself failed. `Unknown` is included because a rolling deploy surfaces as+ // `Unavailable`, not `Unknown`, so `Unknown` is more often a server-side panic.+ tonic::Code::Internal+ | tonic::Code::DataLoss+ | tonic::Code::Unknown+ | tonic::Code::Ok => Some(UcsKillSwitchReason::UcsInternalError),+ },++ // Could not reach UCS at all. Same treatment as `Unavailable` above.+ Self::ConnectionError(_) => Some(UcsKillSwitchReason::UcsUnreachable),++ // No usable status never reaches here: `from_grpc_error` falls through to+ // `TonicStatus`. A zero means UCS supplied one, which is UCS-side.+ Self::ConnectorError(inner) if inner.status_code == 0 => {+ Some(UcsKillSwitchReason::UcsInternalError)+ }++ // The connector answered. This may be a legitimate decline or a request UCS built+ // wrongly — indistinguishable here. We trip conservatively: a false bypass to the+ // direct path is safe (it served merchants for years), while a missed trip leaves+ // merchants on a potentially broken UCS path.+ Self::ConnectorError(_) => Some(UcsKillSwitchReason::ConnectorOutcome),++ // Per-flow failure markers carrying no further detail.+ Self::WebhookProcessingFailure+ | Self::PaymentCreateOrderFailure+ | Self::PaymentAuthorizeGranularFailure+ | Self::CreateSessionTokenFailure+ | Self::CreateAccessTokenFailure+ | Self::PaymentMethodTokenizeFailure+ | Self::CreateConnectorCustomerFailure+ | Self::PaymentAuthorizeFailure+ | Self::PaymentPreAuthenticateFailure+ | Self::PaymentAuthenticateFailure+ | Self::PaymentPostAuthenticateFailure+ | Self::PaymentGetFailure+ | Self::PaymentCaptureFailure+ | Self::PaymentSetupRecurringFailure+ | Self::RecurringPaymentChargeFailure+ | Self::PaymentRefundFailure+ | Self::RefundSyncFailure+ | Self::IncomingWebhookHandleEventFailure+ | Self::IncomingWebhookParseEventFailure+ | Self::PaymentVoidFailure+ | Self::CreateSdkSessionTokenFailure+ | Self::PaymentIncrementalAuthorizationFailure+ | Self::PayoutCreateFailure+ | Self::PayoutTransferFailure+ | Self::PayoutGetFailure+ | Self::PayoutVoidFailure+ | Self::PayoutStageFailure+ | Self::PayoutCreateRecipientFailure+ | Self::PayoutEnrollDisburseAccountFailure+ | Self::SurchargeCalculateFailure+ | Self::NotifyConnectorFailure => Some(UcsKillSwitchReason::UcsInternalError),+ }+ }+}++#[cfg(test)]+mod ucs_kill_switch_reason_tests {+ use super::*;++ fn tonic_status(code: tonic::Code) -> UnifiedConnectorServiceError {+ UnifiedConnectorServiceError::TonicStatus {+ code,+ message: "from ucs".to_string(),+ }+ }++ #[test]+ fn ucs_wide_grpc_codes_still_qualify() {+ // While UCS is unwell the payment has no fallback and fails outright, so these qualify+ // like any other. They share a label so a run of them reads as one UCS-wide event.+ for code in [+ tonic::Code::Unavailable,+ tonic::Code::DeadlineExceeded,+ tonic::Code::ResourceExhausted,+ tonic::Code::Aborted,+ tonic::Code::Cancelled,+ ] {+ assert_eq!(+ tonic_status(code).ucs_kill_switch_reason(),+ Some(UcsKillSwitchReason::UcsUnreachable),+ "{code:?}"+ );+ }+ }++ #[test]+ fn ucs_side_grpc_codes_are_kill_switch_worthy() {+ // `from_grpc_error` extracts connector errors and timeouts before producing TonicStatus,+ // so what reaches here is UCS-side and repeats identically for this scope.+ let cases = [+ (+ tonic::Code::InvalidArgument,+ UcsKillSwitchReason::UcsRejectedRequest,+ ),+ (+ tonic::Code::FailedPrecondition,+ UcsKillSwitchReason::UcsRejectedRequest,+ ),+ (+ tonic::Code::Unauthenticated,+ UcsKillSwitchReason::UcsRejectedRequest,+ ),+ (+ tonic::Code::Unimplemented,+ UcsKillSwitchReason::UcsFlowUnsupported,+ ),+ (tonic::Code::Internal, UcsKillSwitchReason::UcsInternalError),+ (tonic::Code::Unknown, UcsKillSwitchReason::UcsInternalError),+ ];++ for (code, expected) in cases {+ assert_eq!(+ tonic_status(code).ucs_kill_switch_reason(),+ Some(expected),+ "{code:?}"+ );+ }+ }+}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 9fc90247dc..7ad43639a6 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -365,6 +365,19 @@ pub const UCS_ROLLOUT_CONFIG_NOT_CONFIGURED: &str = "not_configured";// UCS feature enabled configpub const UCS_ENABLED: &str = "ucs_enabled";+// Config key gating the UCS kill switch. Read through the same cached config lookup as+// `UCS_ENABLED`, so the switch can be turned on or off without a redeploy.+pub const UCS_KILL_SWITCH_ENABLED: &str = "ucs_kill_switch_enabled";++// Prefix of the redis key holding a kill switch trip. Absent until a scope trips.+pub const UCS_KILL_SWITCH_REDIS_PREFIX: &str = "ucs_kill_switch";++// Lifetime of a trip, in seconds. A trip is meant to be cleared by an operator, but+// `redis_interface` has no setter that writes a key without an expiry, so it is spelled as a+// bound rather than left open. A week outlives a long weekend; a still-broken scope trips again+// on its next request.+pub const UCS_KILL_SWITCH_TTL_IN_SECONDS: i64 = 7 * 24 * 60 * 60;+/// Header value indicating that signature-key-based authentication is used.pub const UCS_AUTH_SIGNATURE_KEY: &str = "signature-key";diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rsindex 18b70053ca..f58be0f8ed 100644--- a/crates/router/src/core/metrics.rs+++ b/crates/router/src/core/metrics.rs@@ -94,6 +94,12 @@ counter_metric!(DECISION_ENGINE_REQUESTS, GLOBAL_METER);counter_metric!(DECISION_ENGINE_ROUTING_DIFF, GLOBAL_METER);counter_metric!(DECISION_ENGINE_KILL_SWITCH_TRIGGERED, GLOBAL_METER);+// Qualifying UCS failures seen by the kill switch, emitted whether or not it is turned on so the+// classifier can be validated against real traffic before the switch is turned on.+counter_metric!(UCS_KILL_SWITCH_FAILURE, GLOBAL_METER);+// Scopes tripped back to the direct integration.+counter_metric!(UCS_KILL_SWITCH_TRIPPED, GLOBAL_METER);+#[cfg(feature = "partial-auth")]counter_metric!(PARTIAL_AUTH_FAILURE, GLOBAL_METER);diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 9613e74c31..d534fabad4 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2501,15 +2501,12 @@ pub fn decide_payment_method_retrieval_action(}}-pub async fn is_ucs_enabled(state: &SessionState, config_key: &str) -> bool {+pub async fn is_config_flag_enabled(state: &SessionState, config_key: &str) -> bool {let db = state.store.as_ref();db.find_config_by_key_unwrap_or(config_key, Some("false".to_string())).await.inspect_err(|error| {- logger::error!(- ?error,- "Failed to fetch `{config_key}` UCS enabled config from DB"- );+ logger::error!(?error, "Failed to fetch `{config_key}` config from DB");}).ok().and_then(|config| {@@ -2517,7 +2514,7 @@ pub async fn is_ucs_enabled(state: &SessionState, config_key: &str) -> bool {.config.parse::<bool>().inspect_err(|error| {- logger::error!(?error, "Failed to parse `{config_key}` UCS enabled config");+ logger::error!(?error, "Failed to parse `{config_key}` config");}).ok()})diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex 71c50d86c4..6b4ed515ee 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -637,6 +637,9 @@ async fn execute_refund_execute_via_direct_with_ucs_shadow(Err(e) => Err(format!("{:?}", e)),};let connector_name = router_data.connector.clone();+ let merchant_id = router_data.merchant_id.clone();+ let payment_method = router_data.payment_method;+ let payment_method_type = router_data.payment_method_type;tokio::spawn((async move {@@ -661,6 +664,9 @@ async fn execute_refund_execute_via_direct_with_ucs_shadow(connector_name,direct_for_compare,ucs_for_compare,+ Some(&merchant_id),+ Some(payment_method),+ payment_method_type,),).await;@@ -1183,6 +1189,9 @@ async fn execute_refund_sync_via_direct_with_ucs_shadow(Err(e) => Err(format!("{:?}", e)),};let connector_name = router_data.connector.clone();+ let merchant_id = router_data.merchant_id.clone();+ let payment_method = router_data.payment_method;+ let payment_method_type = router_data.payment_method_type;tokio::spawn((async move {@@ -1207,6 +1216,9 @@ async fn execute_refund_sync_via_direct_with_ucs_shadow(connector_name,direct_for_compare,ucs_for_compare,+ Some(&merchant_id),+ Some(payment_method),+ payment_method_type,),).await;diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 390a84d140..c248721014 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -46,7 +46,7 @@ use crate::{errors::{self, RouterResult},payments::{helpers::{- is_googlepay_predecrypted_flow_supported, is_ucs_enabled,+ is_config_flag_enabled, is_googlepay_predecrypted_flow_supported,should_execute_based_on_rollout, should_execute_based_on_rollout_with_precedence,MerchantConnectorAccountType, ProxyOverride, WebhookRolloutConfig,WebhookRolloutExecutionResult,@@ -68,6 +68,7 @@ use crate::{};pub mod connector_config;+pub mod kill_switch;pub mod transformers;/// Returns Apple Pay data from payment method token when it has decrypt data,@@ -239,7 +240,7 @@ type UnifiedConnectorServiceCreateOrderResult = CustomResult<async fn check_ucs_availability(state: &SessionState) -> UcsAvailability {let is_client_available = state.grpc_client.unified_connector_service_client.is_some();- let is_enabled = is_ucs_enabled(state, consts::UCS_ENABLED).await;+ let is_enabled = is_config_flag_enabled(state, consts::UCS_ENABLED).await;match (is_client_available, is_enabled) {(true, true) => {@@ -325,7 +326,7 @@ where// 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(+ | common_enums::TransactionType::ThreeDsAuthentication => build_rollout_keys_by_precedence(org_id,merchant_id,connector_name,@@ -350,7 +351,8 @@ whereshould_execute_based_on_rollout_with_precedence(state, &rollout_keys).await?;// Single decision point using pattern matching- let (gateway_system, mut execution_path) = if ucs_availability == UcsAvailability::Disabled {+ let (mut gateway_system, mut execution_path) = if ucs_availability == UcsAvailability::Disabled+ {match call_connector_action {CallConnectorAction::UCSConsumeResponse(_) => {Err(errors::ApiErrorResponse::InternalServerError)@@ -405,6 +407,36 @@ where}};+ // Kill switch: a scope that already failed deterministically serves from the direct+ // integration regardless of what its rollout config says.+ //+ // Only the primary path is diverted, and it is diverted to shadow rather than to direct — the+ // merchant is served by the direct integration either way, but shadow keeps mirroring, so a+ // tripped scope still produces the comparison signal needed to confirm a fix before it is+ // reset. Shadow itself falls back to direct below when no proxy override is configured.+ if matches!(execution_path, ExecutionPath::UnifiedConnectorService)+ && is_kill_switch_applicable(connector_integration_type, &call_connector_action)+ {+ let rollout_scope = build_merchant_rollout_scope(+ merchant_id,+ connector_name,+ &flow_name,+ router_data.payment_method,+ router_data.payment_method_type,+ );++ if Box::pin(kill_switch::is_tripped(state, &rollout_scope)).await {+ router_env::logger::warn!(+ merchant_id = %merchant_id,+ connector = %connector_name,+ flow = %flow_name,+ "UCS kill switch is tripped for this scope, serving from the direct integration"+ );+ gateway_system = GatewaySystem::Direct;+ execution_path = ExecutionPath::ShadowUnifiedConnectorService;+ }+ }+// Handle proxy configuration for Shadow UCS flowslet session_state = match execution_path {ExecutionPath::ShadowUnifiedConnectorService => {@@ -467,6 +499,29 @@ fn create_updated_session_state_with_proxy(updated_state}+/// Whether the kill switch may divert this call away from UCS.+///+/// Two cases have nothing to fall back to, so diverting them would not protect the merchant — it+/// would be the outage:+///+/// - [`ConnectorIntegrationType::UcsConnector`] connectors are served only by UCS. There are live+/// merchants on these today, and the direct implementations behind them have never taken+/// production traffic.+/// - [`CallConnectorAction::UCSConsumeResponse`] carries a response UCS has already produced;+/// handing it to any other gateway errors out, as the `UcsAvailability::Disabled` arm shows.+fn is_kill_switch_applicable(+ connector_integration_type: ConnectorIntegrationType,+ call_connector_action: &CallConnectorAction,+) -> bool {+ !matches!(+ connector_integration_type,+ ConnectorIntegrationType::UcsConnector+ ) && !matches!(+ call_connector_action,+ CallConnectorAction::UCSConsumeResponse(_)+ )+}+fn decide_execution_path(connector_type: ConnectorIntegrationType,previous_gateway: Option<GatewaySystem>,@@ -536,49 +591,35 @@ fn decide_execution_path(}}-/// 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 merchant level of a rollout key: merchant, connector, payment method and flow.///-/// The caller iterates highest → lowest and uses the first match found.-fn build_rollout_keys(- org_id: &str,+/// The finest of the four precedence levels, and the only one that varies by connector or+/// payment method. Shared with the kill switch so a trip targets exactly the key that enabled+/// the traffic.+pub fn build_merchant_rollout_scope(merchant_id: &str,connector_name: &str,flow_name: &str,payment_method: common_enums::PaymentMethod,payment_method_type: Option<PaymentMethodType>,-) -> Vec<String> {- let prefix = consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX;- let is_refund_flow = matches!(flow_name, "Execute" | "RSync");+) -> String {+ let payment_method_str = payment_method.to_string();- 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 {+ match flow_name {+ // Refund keys carry no payment method.+ "Execute" | "RSync" => format!("{merchant_id}_{connector_name}_{flow_name}"),++ _ => match payment_method {+ // These payment methods are discriminated further by payment method type.common_enums::PaymentMethod::Wallet| common_enums::PaymentMethod::BankRedirect| common_enums::PaymentMethod::Voucher| common_enums::PaymentMethod::PayLater => {- let payment_method_str = payment_method.to_string();let payment_method_type_str = payment_method_type.map(|pmt| pmt.to_string()).unwrap_or_else(|| "unknown".to_string());- (- 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}"),+ format!(+ "{merchant_id}_{connector_name}_{payment_method_str}_{payment_method_type_str}_{flow_name}")}common_enums::PaymentMethod::Card@@ -593,22 +634,36 @@ fn build_rollout_keys(| common_enums::PaymentMethod::MobilePayment| common_enums::PaymentMethod::NetworkToken| common_enums::PaymentMethod::OpenBanking => {- // For other payment methods, use a generic format without specific payment method type details- let payment_method_str = payment_method.to_string();- (- format!("{prefix}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),- format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),- )+ format!("{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}")}- }- };+ },+ }+}++/// Rollout config keys, **lowest precedence first**. The caller reverses this and takes the+/// first key that exists, so the order is load-bearing.+fn build_rollout_keys_by_precedence(+ org_id: &str,+ merchant_id: &str,+ connector_name: &str,+ flow_name: &str,+ payment_method: common_enums::PaymentMethod,+ payment_method_type: Option<PaymentMethodType>,+) -> Vec<String> {+ let prefix = consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX;+ let scope = build_merchant_rollout_scope(+ merchant_id,+ connector_name,+ flow_name,+ payment_method,+ payment_method_type,+ );- // 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,+ format!("{prefix}_{org_id}_{scope}"),+ format!("{prefix}_{scope}"),]}@@ -3042,6 +3097,8 @@ wherelet refund_id = router_data.refund_id.clone();let dispute_id = router_data.dispute_id.clone();let payout_id = router_data.payout_id.clone();+ let payment_method = router_data.payment_method;+ let payment_method_type = router_data.payment_method_type;let grpc_header = grpc_header_builder.build();// Log the actual gRPC request with maskinglet grpc_request_body = hyperswitch_masking::masked_serialize(&grpc_request)@@ -3093,6 +3150,34 @@ whererouter_env::metric_attributes!(("connector", connector_name.clone(),)),);+ // Every payment and payout gateway funnels through here with the UCS error still+ // typed, so this is the one place the kill switch has to observe.+ match get_flow_name::<T>() {+ Ok(flow_name) => {+ kill_switch::record_failure(+ state,+ kill_switch::UcsFailureContext {+ merchant_id: merchant_id.get_string_repr(),+ connector_name: &connector_name,+ flow_name: &flow_name,+ payment_id: &payment_id,+ payment_method,+ payment_method_type,+ },+ execution_mode,+ error.current_context(),+ )+ .await;+ }+ // Never expected, but skipping here would disable the kill switch for this flow+ // without saying so.+ Err(flow_name_error) => logger::error!(+ ?flow_name_error,+ connector = %connector_name,+ "ucs_kill_switch: could not resolve the flow name, failure not classified"+ ),+ }+let error_body = serde_json::json!({"error": error.to_string(),"error_type": "ucs_call_failed"@@ -3267,6 +3352,14 @@ pub async fn call_unified_connector_service_for_refund_execute(let prev_refund_status = router_data.request.refund_status;+ // Captured before `router_data` moves into the wrapper, so the kill switch can build the same+ // scope the gateway decision built.+ let merchant_id_for_kill_switch = processor.get_account().get_id().clone();+ let connector_name_for_kill_switch = router_data.connector.clone();+ let payment_method_for_kill_switch = router_data.payment_method;+ let payment_method_type_for_kill_switch = router_data.payment_method_type;+ let payment_id_for_kill_switch = router_data.payment_id.clone();+// Make UCS refund call with logging wrapperBox::pin(ucs_logging_wrapper(router_data,@@ -3282,6 +3375,23 @@ pub async fn call_unified_connector_service_for_refund_execute({Ok(resp) => resp,Err(report) => {+ // Recorded before the connector-error branch below returns `Ok`, so a refund+ // decline is classified on the same footing as a payment one.+ kill_switch::record_failure(+ state,+ kill_switch::UcsFailureContext {+ merchant_id: merchant_id_for_kill_switch.get_string_repr(),+ connector_name: &connector_name_for_kill_switch,+ flow_name: "Execute",+ payment_id: &payment_id_for_kill_switch,+ payment_method: payment_method_for_kill_switch,+ payment_method_type: payment_method_type_for_kill_switch,+ },+ execution_mode,+ report.current_context(),+ )+ .await;+if let UnifiedConnectorServiceError::ConnectorError(inner) =report.current_context(){@@ -3403,6 +3513,14 @@ pub async fn call_unified_connector_service_for_refund_sync(let prev_refund_status = router_data.request.refund_status;+ // Captured before `router_data` moves into the wrapper, so the kill switch can build the same+ // scope the gateway decision built.+ let merchant_id_for_kill_switch = processor.get_account().get_id().clone();+ let connector_name_for_kill_switch = router_data.connector.clone();+ let payment_method_for_kill_switch = router_data.payment_method;+ let payment_method_type_for_kill_switch = router_data.payment_method_type;+ let payment_id_for_kill_switch = router_data.payment_id.clone();+// Make UCS refund sync call with logging wrapperBox::pin(ucs_logging_wrapper(router_data,@@ -3418,6 +3536,23 @@ pub async fn call_unified_connector_service_for_refund_sync({Ok(resp) => resp,Err(report) => {+ // Recorded before the connector-error branch below returns `Ok`, so a refund+ // decline is classified on the same footing as a payment one.+ kill_switch::record_failure(+ state,+ kill_switch::UcsFailureContext {+ merchant_id: merchant_id_for_kill_switch.get_string_repr(),+ connector_name: &connector_name_for_kill_switch,+ flow_name: "RSync",+ payment_id: &payment_id_for_kill_switch,+ payment_method: payment_method_for_kill_switch,+ payment_method_type: payment_method_type_for_kill_switch,+ },+ execution_mode,+ report.current_context(),+ )+ .await;+if let UnifiedConnectorServiceError::ConnectorError(inner) =report.current_context(){diff --git a/crates/router/src/core/unified_connector_service/kill_switch.rs b/crates/router/src/core/unified_connector_service/kill_switch.rsnew file mode 100644index 0000000000..ea9bf53845--- /dev/null+++ b/crates/router/src/core/unified_connector_service/kill_switch.rs@@ -0,0 +1,551 @@+//! Returns a rollout scope to the direct connector integration when a Unified Connector Service+//! call fails.+//!+//! Trips live in redis, keyed on the rollout scope; `ucs_rollout_config` rows are never written+//! to. Ambiguous outcomes resolve towards the direct path, which is what the scope used before+//! UCS.++use std::str::FromStr;++use common_enums::{connector_enums::Connector, ConnectorIntegrationType, ExecutionMode};+use error_stack::ResultExt;+use hyperswitch_interfaces::unified_connector_service::transformers::{+ UcsKillSwitchReason, UnifiedConnectorServiceError,+};+use router_env::logger;++use crate::{+ consts,+ core::{+ errors, metrics,+ payments::helpers::is_config_flag_enabled,+ unified_connector_service::{+ build_merchant_rollout_scope, determine_connector_integration_type,+ },+ },+ routes::SessionState,+};++/// Redis key holding the trip for a scope.+fn trip_key(rollout_scope: &str) -> String {+ format!("{}_{rollout_scope}", consts::UCS_KILL_SWITCH_REDIS_PREFIX)+}++/// The rollout scope inside a redis key, or the input unchanged when it is already a scope.+///+/// `scan` hands back whole keys with the tenant prefix in front, and an operator may paste one of+/// those into the reset endpoint, so both callers need the scope back out.+fn rollout_scope_in(key_or_scope: &str) -> &str {+ let prefix = format!("{}_", consts::UCS_KILL_SWITCH_REDIS_PREFIX);++ match key_or_scope.split_once(prefix.as_str()) {+ Some((_, rollout_scope)) => rollout_scope,+ None => key_or_scope,+ }+}++/// Whether the kill switch has tripped for this scope.+///+/// Fails closed: a redis error routes to the direct integration. Only reached once the rollout+/// config resolved to primary, so shadow traffic never pays for the lookup.+pub async fn is_tripped(state: &SessionState, rollout_scope: &str) -> bool {+ if is_config_flag_enabled(state, consts::UCS_KILL_SWITCH_ENABLED).await {+ match read_trip(state, rollout_scope).await {+ Ok(tripped) => tripped,+ // Fails closed: the scope goes to the direct integration when redis cannot answer.+ Err(error) => {+ logger::error!(+ ?error,+ rollout_scope = %rollout_scope,+ "ucs_kill_switch: trip unreadable, routing to the direct integration"+ );+ true+ }+ }+ } else {+ false+ }+}++/// Reads the trip. Redis failures short-circuit to the caller, which decides the safe answer.+async fn read_trip(+ state: &SessionState,+ rollout_scope: &str,+) -> error_stack::Result<bool, storage_impl::errors::RedisError> {+ let tripped = state+ .store+ .get_redis_conn()?+ .exists::<()>(&trip_key(rollout_scope).as_str().into())+ .await?;++ if tripped {+ // Every request for a tripped scope reaches here; the trip is logged once elsewhere.+ logger::debug!(+ rollout_scope = %rollout_scope,+ "ucs_kill_switch: scope is tripped, routing to the direct integration"+ );+ }++ Ok(tripped)+}++/// What a failing UCS call was for. A struct because transposing two of six positional strings+/// would key trips under the wrong scope.+pub struct UcsFailureContext<'a> {+ pub merchant_id: &'a str,+ pub connector_name: &'a str,+ pub flow_name: &'a str,+ pub payment_id: &'a str,+ pub payment_method: common_enums::PaymentMethod,+ pub payment_method_type: Option<common_enums::PaymentMethodType>,+}++/// A failure that qualifies to trip, and the scope it would trip.+struct TrippableFailure {+ rollout_scope: String,+ reason: UcsKillSwitchReason,+}++/// Records a qualifying UCS failure, and trips its scope when the switch is turned on.+///+/// Never returns an error: it runs on an already-failing path and must not fail the request.+pub async fn record_failure(+ state: &SessionState,+ context: UcsFailureContext<'_>,+ execution_mode: ExecutionMode,+ error: &UnifiedConnectorServiceError,+) {+ if let Some(failure) = trippable_failure(state, &context, execution_mode, error).await {+ record_trippable_failure(state, &failure, &context, error).await;+ }+}++/// Counts the failure, trips its scope when the switch is turned on, and reports what happened.+async fn record_trippable_failure(+ state: &SessionState,+ failure: &TrippableFailure,+ context: &UcsFailureContext<'_>,+ error: &UnifiedConnectorServiceError,+) {+ metrics::UCS_KILL_SWITCH_FAILURE.add(+ 1,+ router_env::metric_attributes!(+ ("connector", context.connector_name.to_string()),+ ("flow", context.flow_name.to_string()),+ ("reason", failure.reason.to_string())+ ),+ );++ let outcome = if is_config_flag_enabled(state, consts::UCS_KILL_SWITCH_ENABLED).await {+ trip(state, failure, context).await+ } else {+ TripOutcome::SwitchOff+ };++ // The one line this path emits, carrying every dimension of the decision. Alert on `outcome`+ // rather than on a message: `tripped` means a scope left UCS, `write_failed` means one should+ // have and did not. While the switch is off every line reads `switch_off`, which is the feed+ // for validating the classifier against real traffic before turning it on.+ logger::warn!(+ rollout_scope = %failure.rollout_scope,+ merchant_id = %context.merchant_id,+ connector = %context.connector_name,+ flow = %context.flow_name,+ payment_method = %context.payment_method,+ payment_id = %context.payment_id,+ request_id = ?state.request_id,+ reason = %failure.reason,+ outcome = %outcome,+ ucs_error = ?error,+ "ucs_kill_switch"+ );+}++/// What this failure would trip, or `None` when nothing can come of it: shadow traffic, a+/// UCS-only connector the gate never diverts, or a failure the classifier does not qualify.+async fn trippable_failure(+ state: &SessionState,+ context: &UcsFailureContext<'_>,+ execution_mode: ExecutionMode,+ error: &UnifiedConnectorServiceError,+) -> Option<TrippableFailure> {+ // Only the path serving merchant traffic can trip, and only a connector that has a direct+ // integration to fall back to. `&&` keeps the cheap check first.+ let scope_can_trip = matches!(execution_mode, ExecutionMode::Primary)+ && !is_ucs_only_connector(state, context.connector_name).await;++ scope_can_trip+ .then(|| error.ucs_kill_switch_reason())+ .flatten()+ .map(|reason| TrippableFailure {+ rollout_scope: build_merchant_rollout_scope(+ context.merchant_id,+ context.connector_name,+ context.flow_name,+ context.payment_method,+ context.payment_method_type,+ ),+ reason,+ })+}++/// A UCS-only connector has no direct integration to fall back to, so the gate never diverts one.+/// An unparseable connector name counts as having one, rather than silently dropping a scope that+/// can trip.+async fn is_ucs_only_connector(state: &SessionState, connector_name: &str) -> bool {+ match Connector::from_str(connector_name) {+ Ok(connector) => matches!(+ determine_connector_integration_type(state, connector).await,+ Ok(ConnectorIntegrationType::UcsConnector)+ ),+ Err(_) => false,+ }+}++/// What came of a trippable failure. Reported as a field on the one line the recording path+/// emits, so an alert keys on the outcome rather than on several message strings.+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display)]+#[strum(serialize_all = "snake_case")]+enum TripOutcome {+ /// This pod wrote the trip. The scope now serves from the direct integration.+ Tripped,+ /// Another pod wrote it first.+ AlreadyTripped,+ /// The failure qualified, but enforcement is turned off.+ SwitchOff,+ /// Redis refused the write, so the scope stays on UCS.+ WriteFailed,+}++/// Writes the trip. `SET NX` makes it exactly-once: one concurrent writer wins, the rest no-op.+async fn trip(+ state: &SessionState,+ failure: &TrippableFailure,+ context: &UcsFailureContext<'_>,+) -> TripOutcome {+ let TrippableFailure {+ rollout_scope,+ reason,+ } = failure;++ let record = TripRecord {+ reason: reason.to_string(),+ request_id: state.request_id.as_ref().map(|id| id.to_string()),+ tripped_at: common_utils::date_time::now_unix_timestamp(),+ };++ match write_trip(state, rollout_scope, &record).await {+ Ok(redis_interface::SetnxReply::KeySet) => {+ metrics::UCS_KILL_SWITCH_TRIPPED.add(+ 1,+ router_env::metric_attributes!(+ ("connector", context.connector_name.to_string()),+ ("flow", context.flow_name.to_string()),+ ("reason", reason.to_string())+ ),+ );++ TripOutcome::Tripped+ }+ Ok(redis_interface::SetnxReply::KeyNotSet) => TripOutcome::AlreadyTripped,+ // The cause does not belong on the summary line, and it is the one thing an operator+ // cannot act on without it.+ Err(error) => {+ logger::error!(+ ?error,+ rollout_scope = %rollout_scope,+ "ucs_kill_switch: could not persist the trip"+ );++ TripOutcome::WriteFailed+ }+ }+}++/// Writes the trip if no other pod got there first. Serialisation and redis failures alike+/// short-circuit to the caller, which logs them on one path.+async fn write_trip(+ state: &SessionState,+ rollout_scope: &str,+ record: &TripRecord,+) -> error_stack::Result<redis_interface::SetnxReply, storage_impl::errors::RedisError> {+ let record = serde_json::to_string(record)+ .change_context(storage_impl::errors::RedisError::JsonSerializationFailed)?;++ state+ .store+ .get_redis_conn()?+ .set_key_if_not_exists_with_expiry(+ &trip_key(rollout_scope).as_str().into(),+ record,+ Some(consts::UCS_KILL_SWITCH_TTL_IN_SECONDS),+ )+ .await+}++/// What was written when a scope tripped. Enough to find the originating request; the error+/// itself stays out, being unbounded and unmasked connector text that the alert log already+/// carries against the same request id.+#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub struct TripRecord {+ pub reason: String,+ pub request_id: Option<String>,+ pub tripped_at: i64,+}++/// Whether a scope is tripped, and what tripped it. `trip` is absent when the scope is not+/// tripped, or when its record predates this shape.+#[derive(Debug, serde::Serialize)]+pub struct KillSwitchStatusResponse {+ pub rollout_scope: String,+ pub tripped: bool,+ pub trip: Option<TripRecord>,+}++impl common_utils::events::ApiEventMetric for KillSwitchStatusResponse {}++/// Clears the trip, returning the scope to whatever its rollout config says. Takes either form+/// the list endpoint hands back.+pub async fn reset(state: SessionState, listed_key: String) -> errors::RouterResponse<()> {+ let rollout_scope = rollout_scope_in(&listed_key);++ let reply = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get a redis connection to clear the UCS kill switch")?+ .delete_key(&trip_key(rollout_scope).as_str().into())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to delete the UCS kill switch trip")?;++ match reply {+ redis_interface::DelReply::KeyDeleted => {+ logger::info!(+ rollout_scope = %rollout_scope,+ "ucs_kill_switch: trip cleared via api"+ );++ Ok(crate::services::ApplicationResponse::StatusOk)+ }+ // Redis reports a missing key as a successful delete of nothing. Reporting that as+ // success would tell an operator a scope is back on UCS when a mistyped scope left it+ // tripped.+ redis_interface::DelReply::KeyNotDeleted => {+ Err(errors::ApiErrorResponse::GenericNotFoundError {+ message: format!("No UCS kill switch trip found for scope {rollout_scope}"),+ }+ .into())+ }+ }+}++/// Whether this scope is tripped, and what tripped it. Reads the trip record so an on-call+/// engineer has that without redis or log access. One key, so no keyspace walk.+pub async fn trip_status(+ state: SessionState,+ key_or_scope: String,+) -> errors::RouterResponse<KillSwitchStatusResponse> {+ let rollout_scope = rollout_scope_in(&key_or_scope);++ let record = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get a redis connection to read the UCS kill switch trip")?+ .get_key::<Option<String>>(&trip_key(rollout_scope).as_str().into())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to read the UCS kill switch trip")?;++ Ok(crate::services::ApplicationResponse::Json(+ KillSwitchStatusResponse {+ rollout_scope: rollout_scope.to_string(),+ tripped: record.is_some(),+ // A record written by an older build may not parse; the scope is still tripped.+ trip: record.and_then(|record| serde_json::from_str::<TripRecord>(&record).ok()),+ },+ ))+}++#[cfg(test)]+mod tests {+ use common_enums::{PaymentMethod, PaymentMethodType};++ use super::*;++ /// A connector's own answer, arriving through UCS.+ fn connector_error(status_code: u16) -> UnifiedConnectorServiceError {+ UnifiedConnectorServiceError::ConnectorError(Box::new(+ hyperswitch_interfaces::unified_connector_service::transformers::ConnectorErrorInner {+ code: "card_declined".to_string(),+ message: "Card was declined".to_string(),+ status_code,+ reason: None,+ connector: "cybersource".to_string(),+ connector_transaction_id: None,+ network_decline_code: None,+ network_advice_code: None,+ network_error_message: None,+ },+ ))+ }++ /// One merchant and connector, so a case reads as just its payment method and flow.+ fn rollout_scope(+ payment_method: PaymentMethod,+ pmt: Option<PaymentMethodType>,+ flow: &str,+ ) -> String {+ build_merchant_rollout_scope("merchant_1", "cybersource", flow, payment_method, pmt)+ }++ #[test]+ fn failures_are_labelled_by_where_they_originated() {+ let cases = [+ (+ UnifiedConnectorServiceError::ResponseDeserializationFailed,+ UcsKillSwitchReason::HyperswitchResponseUndecodable,+ ),+ (+ UnifiedConnectorServiceError::ParsingFailed,+ UcsKillSwitchReason::HyperswitchResponseUndecodable,+ ),+ (+ UnifiedConnectorServiceError::RequestEncodingFailed,+ UcsKillSwitchReason::HyperswitchRequestInvalid,+ ),+ (+ UnifiedConnectorServiceError::FailedToObtainAuthType,+ UcsKillSwitchReason::HyperswitchRequestInvalid,+ ),+ (+ UnifiedConnectorServiceError::MissingRequiredField {+ field_name: "payment_method_data",+ },+ UcsKillSwitchReason::HyperswitchRequestInvalid,+ ),+ (+ UnifiedConnectorServiceError::NotImplemented("PSync".into()),+ UcsKillSwitchReason::UcsFlowUnsupported,+ ),+ ];++ for (error, expected) in cases {+ assert_eq!(error.ucs_kill_switch_reason(), Some(expected), "{error:?}");+ }+ }++ #[test]+ fn an_unreachable_ucs_trips() {+ // While UCS is unreachable the payment has no fallback and fails outright, so serving+ // from the direct integration is strictly better.+ assert_eq!(+ UnifiedConnectorServiceError::ConnectionError("dial".into()).ucs_kill_switch_reason(),+ Some(UcsKillSwitchReason::UcsUnreachable)+ );+ }++ #[test]+ fn connector_outcomes_trip_conservatively() {+ // A false bypass to the direct path is safe — it served merchants for years.+ // A missed trip leaves merchants on a potentially broken UCS path.+ let cases = [+ connector_error(402),+ connector_error(504),+ connector_error(500),+ ];++ for error in cases {+ assert_eq!(+ error.ucs_kill_switch_reason(),+ Some(UcsKillSwitchReason::ConnectorOutcome),+ "{error:?}"+ );+ }+ }++ #[test]+ fn scope_is_the_rollout_key_without_its_prefix() {+ // A trip must target exactly the rollout key that enabled the traffic.+ assert_eq!(+ rollout_scope(PaymentMethod::Card, None, "Authorize"),+ "merchant_1_cybersource_card_Authorize"+ );+ // Wallets carry a payment method type, exactly as their rollout keys do.+ assert_eq!(+ rollout_scope(+ PaymentMethod::Wallet,+ Some(PaymentMethodType::GooglePay),+ "Authorize"+ ),+ "merchant_1_cybersource_wallet_google_pay_Authorize"+ );+ // Refund keys carry no payment method.+ assert_eq!(+ rollout_scope(PaymentMethod::Card, None, "Execute"),+ "merchant_1_cybersource_Execute"+ );+ }++ #[test]+ fn independently_enabled_keys_trip_independently() {+ // Card and wallet are enabled by separate rollout keys, and wallets fail differently,+ // so a wallet trip must not take card traffic with it.+ let card = rollout_scope(PaymentMethod::Card, None, "Authorize");++ assert_ne!(+ card,+ rollout_scope(+ PaymentMethod::Wallet,+ Some(PaymentMethodType::GooglePay),+ "Authorize"+ )+ );+ assert_ne!(card, rollout_scope(PaymentMethod::Card, None, "PSync"));+ assert_ne!(+ card,+ build_merchant_rollout_scope(+ "merchant_2",+ "cybersource",+ "Authorize",+ PaymentMethod::Card,+ None+ )+ );+ assert_ne!(+ card,+ build_merchant_rollout_scope(+ "merchant_1",+ "adyen",+ "Authorize",+ PaymentMethod::Card,+ None+ )+ );+ }++ #[test]+ fn trip_key_cannot_collide_with_a_rollout_config_key() {+ let key = trip_key(&rollout_scope(PaymentMethod::Card, None, "Authorize"));++ assert!(key.starts_with(consts::UCS_KILL_SWITCH_REDIS_PREFIX));+ assert!(!key.starts_with(consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX));+ }++ #[test]+ fn failure_reasons_have_distinct_tags() {+ let tags = [+ UcsKillSwitchReason::HyperswitchResponseUndecodable.to_string(),+ UcsKillSwitchReason::HyperswitchRequestInvalid.to_string(),+ UcsKillSwitchReason::UcsRejectedRequest.to_string(),+ UcsKillSwitchReason::UcsFlowUnsupported.to_string(),+ UcsKillSwitchReason::UcsInternalError.to_string(),+ UcsKillSwitchReason::UcsUnreachable.to_string(),+ UcsKillSwitchReason::ConnectorOutcome.to_string(),+ ];+ let unique: std::collections::HashSet<_> = tags.iter().collect();++ assert_eq!(unique.len(), tags.len());+ }+}diff --git a/crates/router/src/core/webhooks/gateway.rs b/crates/router/src/core/webhooks/gateway.rsindex ef2d0d68df..98b63bbd63 100644--- a/crates/router/src/core/webhooks/gateway.rs+++ b/crates/router/src/core/webhooks/gateway.rs@@ -576,11 +576,16 @@ fn spawn_shadow_ucs_run(logger::warn!(?error, "UCS shadow webhook run failed");}let shadow_snapshot = WebhookShadowSnapshot::from_result(&shadow_result);+ let merchant_id = inner_ctx+ .merchant_connector_account+ .as_ref()+ .map(|mca| mca.merchant_id.clone());report_shadow_diff(&inner_ctx.state,&inner_ctx.connector_name,&primary_snapshot,&shadow_snapshot,+ merchant_id,).await;}@@ -687,6 +692,7 @@ async fn report_shadow_diff(connector_name: &str,primary: &WebhookShadowSnapshot,shadow: &WebhookShadowSnapshot,+ merchant_id: Option<common_utils::id_type::MerchantId>,) {logger::info!(primary_event_type = ?primary.event_type,@@ -708,6 +714,7 @@ async fn report_shadow_diff(config,connector_name.to_string(),state.get_request_id_str(),+ merchant_id.as_ref(),).await;}diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex c5e123b634..0e7950b417 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -300,6 +300,7 @@ pub fn mk_app(.service(routes::User::server(state.clone())).service(routes::ApiKeys::server(state.clone())).service(routes::Routing::server(state.clone()))+ .service(routes::UnifiedConnectorService::server(state.clone())).service(routes::Chat::server(state.clone()));#[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))]diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rsindex 489f5bbe28..f0fdb66019 100644--- a/crates/router/src/routes.rs+++ b/crates/router/src/routes.rs@@ -60,6 +60,8 @@ pub mod superposition_sdk_config;pub mod three_ds_decision_rule;pub mod tokenization;#[cfg(feature = "olap")]+pub mod unified_connector_service;+#[cfg(feature = "olap")]pub mod user;#[cfg(feature = "olap")]pub mod user_role;@@ -100,7 +102,9 @@ pub use self::app::{Webhooks,};#[cfg(feature = "olap")]-pub use self::app::{Blocklist, Organization, Routing, Subscription, Verify, WebhookEvents};+pub use self::app::{+ Blocklist, Organization, Routing, Subscription, UnifiedConnectorService, Verify, WebhookEvents,+};#[cfg(feature = "payouts")]pub use self::app::{PayoutLink, Payouts};#[cfg(feature = "v2")]diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex a77988809b..a0a3a0120a 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -62,6 +62,8 @@ use super::refunds;use super::routing;#[cfg(all(feature = "oltp", feature = "v2"))]use super::tokenization as tokenization_routes;+#[cfg(feature = "olap")]+use super::unified_connector_service as unified_connector_service_routes;#[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))]use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};#[cfg(feature = "oltp")]@@ -2327,6 +2329,21 @@ impl Configs {}}+pub struct UnifiedConnectorService;++#[cfg(feature = "olap")]+impl UnifiedConnectorService {+ pub fn server(state: AppState) -> Scope {+ web::scope("/unified-connector-service")+ .app_data(web::Data::new(state))+ .service(+ web::resource("/kill-switch/{scope}")+ .route(web::get().to(unified_connector_service_routes::kill_switch_status))+ .route(web::delete().to(unified_connector_service_routes::reset_kill_switch)),+ )+ }+}+pub struct ApplePayCertificatesMigration;#[cfg(all(feature = "olap", feature = "v1"))]diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex a50f7ab878..ca2c716470 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -119,7 +119,9 @@ impl From<Flow> for ApiIdentifier {| Flow::ConfigKeyFetch| Flow::ConfigKeyUpdate| Flow::ConfigKeyDelete- | Flow::CreateConfigKey => Self::Configs,+ | Flow::CreateConfigKey+ | Flow::UnifiedConnectorServiceKillSwitchStatus+ | Flow::UnifiedConnectorServiceKillSwitchReset => Self::Configs,Flow::CustomersCreate| Flow::CustomersRetrieve| Flow::CustomersRetrieveByReferenceIddiff --git a/crates/router/src/routes/unified_connector_service.rs b/crates/router/src/routes/unified_connector_service.rsnew file mode 100644index 0000000000..d2cbfd77ed--- /dev/null+++ b/crates/router/src/routes/unified_connector_service.rs@@ -0,0 +1,53 @@+use actix_web::{web, HttpRequest, Responder};+use router_env::{instrument, tracing, Flow};++use super::app::AppState;+use crate::{+ core::{api_locking, unified_connector_service::kill_switch},+ services::{api as oss_api, authentication as auth},+};++/// Reports whether the UCS kill switch has tripped a scope, and what tripped it.+///+/// `scope` is the `rollout_scope` the trip logs, or the whole redis key.+#[instrument(skip_all, fields(flow = ?Flow::UnifiedConnectorServiceKillSwitchStatus))]+pub async fn kill_switch_status(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<String>,+) -> impl Responder {+ let flow = Flow::UnifiedConnectorServiceKillSwitchStatus;++ Box::pin(oss_api::server_wrap(+ flow,+ state,+ &req,+ path.into_inner(),+ |state, _, scope, _| kill_switch::trip_status(state, scope),+ &auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++/// Clears a UCS kill switch trip, returning the scope to whatever its rollout config says.+/// Takes the same `scope` as the status endpoint.+#[instrument(skip_all, fields(flow = ?Flow::UnifiedConnectorServiceKillSwitchReset))]+pub async fn reset_kill_switch(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<String>,+) -> impl Responder {+ let flow = Flow::UnifiedConnectorServiceKillSwitchReset;++ Box::pin(oss_api::server_wrap(+ flow,+ state,+ &req,+ path.into_inner(),+ |state, _, scope, _| kill_switch::reset(state, scope),+ &auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 1571be6fd5..e71eb87713 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -661,6 +661,10 @@ pub enum Flow {RoutingEvaluateRule,/// Reset the Decision Engine routing diff kill-switch counter for a profileDecisionEngineDiffCounterReset,+ /// Report whether the Unified Connector Service kill switch has tripped a scope+ UnifiedConnectorServiceKillSwitchStatus,+ /// Clear a Unified Connector Service kill switch cutover+ UnifiedConnectorServiceKillSwitchReset,/// Relay flowRelay,/// Relay retrieve flow