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): disable shadow proxying after transport failures (#14815)
Amitsingh Tanwarc64e26d60c75
diff --git a/config/config.example.toml b/config/config.example.tomlindex af8133962e..a9e6a377dd 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1713,3 +1713,8 @@ refresh_timeout_in_secs = 5 # Optional, defaults to 5. Per-call# (e.g., payment-methods, customers, routing, etc.)payment_methods_base_url = "http://localhost:8082"use_legacy_locker = false # Boolean to enable legacy locker++# Set shadow_kill_switch_threshold = 1 under the existing [comparison_service] section.+# Override using ROUTER__COMPARISON_SERVICE__SHADOW_KILL_SWITCH_THRESHOLD.+# Counts request timeouts, DNS failures, connection refused, and proxy authentication failures.+# Classifies the original shadow request result without additional network checks.diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rsindex dabddd88a5..56e9c52abf 100644--- a/crates/external_services/src/http_client.rs+++ b/crates/external_services/src/http_client.rs@@ -187,22 +187,29 @@ pub async fn send_request(option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT),));+ // Retain the typed cause so callers can distinguish transport errors from+ // request-construction errors within RequestNotSent, including on retries.+ let map_request_error = |error: reqwest::Error| {+ let context = match &error {+ error if error.is_timeout() => {+ metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);+ HttpClientError::RequestTimeoutReceived+ }+ error if is_connection_closed_before_message_could_complete(error) => {+ metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);+ HttpClientError::ConnectionClosedIncompleteMessage+ }+ _ => HttpClientError::RequestNotSent(error.to_string()),+ };+ error_stack::Report::new(error).change_context(context)+ };+// We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here.let cloned_send_request = request.try_clone().map(|cloned_request| async {cloned_request.send().await- .map_err(|error| match error {- error if error.is_timeout() => {- metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);- HttpClientError::RequestTimeoutReceived- }- error if is_connection_closed_before_message_could_complete(&error) => {- metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);- HttpClientError::ConnectionClosedIncompleteMessage- }- _ => HttpClientError::RequestNotSent(error.to_string()),- })+ .map_err(map_request_error).attach_printable("Unable to send request to connector")});@@ -210,17 +217,7 @@ pub async fn send_request(request.send().await- .map_err(|error| match error {- error if error.is_timeout() => {- metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);- HttpClientError::RequestTimeoutReceived- }- error if is_connection_closed_before_message_could_complete(&error) => {- metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag);- HttpClientError::ConnectionClosedIncompleteMessage- }- _ => HttpClientError::RequestNotSent(error.to_string()),- })+ .map_err(map_request_error).attach_printable("Unable to send request to connector")};diff --git a/crates/hyperswitch_interfaces/src/api_client.rs b/crates/hyperswitch_interfaces/src/api_client.rsindex f3302d6e3c..6f64916bf5 100644--- a/crates/hyperswitch_interfaces/src/api_client.rs+++ b/crates/hyperswitch_interfaces/src/api_client.rs@@ -383,6 +383,9 @@ where}?}Err(body) => {+ // Preserve the HTTP status if connector-specific parsing fails.+ let http_status = http::StatusCode::from_u16(body.status_code)+ .unwrap_or(http::StatusCode::INTERNAL_SERVER_ERROR);router_data.connector_http_status_code = Some(body.status_code);router_data.external_latency = Some(router_data@@ -409,7 +412,8 @@ where.get_5xx_error_response(body,Some(&mut connector_event),- )?;+ )+ .attach(http_status)?;state.event_handler().log_connector_event(&connector_event);@@ -420,7 +424,8 @@ where.get_error_response(body,Some(&mut connector_event),- )?;+ )+ .attach(http_status)?;if let Some(status) = error_res.attempt_status {router_data.status = status;};diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rsindex 6cad86175d..1e3881bebf 100644--- a/crates/hyperswitch_interfaces/src/types.rs+++ b/crates/hyperswitch_interfaces/src/types.rs@@ -601,4 +601,11 @@ pub struct ComparisonServiceConfig {pub http_url: String,/// Override HTTPS proxy URL used for UCS rollout proxy switchingpub https_url: String,+ /// Shared shadow request-failure threshold; override with ROUTER__COMPARISON_SERVICE__SHADOW_KILL_SWITCH_THRESHOLD.+ #[serde(default = "default_shadow_kill_switch_threshold")]+ pub shadow_kill_switch_threshold: u64,+}++fn default_shadow_kill_switch_threshold() -> u64 {+ 1}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex e3dab3f241..d86ac9f19e 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -400,6 +400,10 @@ pub const UCS_KILL_SWITCH_REDIS_PREFIX: &str = "ucs_kill_switch";// 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;+/// Global request-failure counter shared by all shadow traffic and pods.+pub const UCS_SHADOW_KILL_SWITCH_REDIS_KEY: &str = "ucs_shadow_killed";+/// Shadow failures expire 24 hours after the latest counter increment.+pub const UCS_SHADOW_KILL_SWITCH_TTL_IN_SECONDS: i64 = 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/payments/access_token.rs b/crates/router/src/core/payments/access_token.rsindex 9e6a57cde4..96e3989b66 100644--- a/crates/router/src/core/payments/access_token.rs+++ b/crates/router/src/core/payments/access_token.rs@@ -4,7 +4,7 @@ use common_enums;use common_utils::ext_traits::AsyncExt;use error_stack::ResultExt;use hyperswitch_interfaces::{- api::{gateway, ConnectorSpecifications, ConnectorValidation},+ api::{ConnectorSpecifications, ConnectorValidation},consts as interfaces_consts,};use unified_connector_service_client::payments as payments_grpc;@@ -13,7 +13,7 @@ use crate::{consts,core::{errors::{self, RouterResult},- payments::{self, gateway::context as gateway_context},+ payments::{self, gateway, gateway::context as gateway_context},unified_connector_service,},routes::{metrics, SessionState},diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rsindex 911e76fb1e..09c90d4c8c 100644--- a/crates/router/src/core/payments/customers.rs+++ b/crates/router/src/core/payments/customers.rs@@ -1,5 +1,5 @@pub use hyperswitch_domain_models::customer::update_connector_customer_in_customers;-use hyperswitch_interfaces::api::{gateway, ConnectorSpecifications};+use hyperswitch_interfaces::api::ConnectorSpecifications;use hyperswitch_masking::PeekInterface;use router_env::{instrument, tracing};@@ -8,7 +8,7 @@ use crate::types::domain;use crate::{core::{errors::{ConnectorErrorExt, RouterResult},- payments::{self, gateway::context as gateway_context},+ payments::{self, gateway, gateway::context as gateway_context},},logger,routes::{metrics, SessionState},diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 476f1563a7..82d95232ed 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -18,7 +18,7 @@ use hyperswitch_domain_models::{router_flow_types, router_request_types, router_response_types,};use hyperswitch_interfaces::{- api::{self as api_interface, gateway, ConnectorSpecifications},+ api::{self as api_interface, ConnectorSpecifications},consts as interface_consts, errors as interface_errors,unified_connector_service::transformers as ucs_transformers,};@@ -39,8 +39,9 @@ use crate::{errors::{ConnectorErrorExt, RouterResult},mandate,payments::{- self, access_token, customers, flows::gateway_context, gateway as payments_gateway,- helpers, session_token, tokenization, transformers, PaymentData,+ self, access_token, customers, flows::gateway_context, gateway,+ gateway as payments_gateway, helpers, session_token, tokenization, transformers,+ PaymentData,},unified_connector_service,},diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex a870c126f9..3690eff244 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -12,10 +12,8 @@ use hyperswitch_domain_models::{router_flow_types, router_request_types, router_response_types,};use hyperswitch_interfaces::{- api as api_interface,- api::{gateway, ConnectorSpecifications},- consts as interface_consts, errors as interface_errors,- unified_connector_service::transformers as ucs_transformers,+ api as api_interface, api::ConnectorSpecifications, consts as interface_consts,+ errors as interface_errors, unified_connector_service::transformers as ucs_transformers,};use hyperswitch_masking::{self, ExposeInterface};use unified_connector_service_client::payments as payments_grpc;@@ -25,8 +23,8 @@ use crate::{core::{errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},payments::{- self, access_token, gateway as payments_gateway, gateway::context as gateway_context,- helpers, transformers, PaymentData,+ self, access_token, gateway, gateway as payments_gateway,+ gateway::context as gateway_context, helpers, transformers, PaymentData,},unified_connector_service as ucs_core,},diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rsindex 5ba790bf26..bc383cb782 100644--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs@@ -10,7 +10,6 @@ use hyperswitch_domain_models::payments::PaymentConfirmData;use hyperswitch_domain_models::{errors::api_error_response::ApiErrorResponse, payments as domain_payments,};-use hyperswitch_interfaces::api::gateway;use hyperswitch_masking::ExposeInterface;use unified_connector_service_client::payments as payments_grpc;@@ -19,7 +18,7 @@ use crate::{core::{errors::{ConnectorErrorExt, RouterResult},payments::{- self, access_token, customers, gateway::context as gateway_context, helpers,+ self, access_token, customers, gateway, gateway::context as gateway_context, helpers,session_token, tokenization, transformers, PaymentData,},unified_connector_service::{self, ucs_logging_wrapper},@@ -159,7 +158,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>connector: &api::ConnectorData,_processor: &domain::Processor,creds_identifier: Option<&str>,- gateway_context: &payments::gateway::context::RouterGatewayContext,+ gateway_context: &gateway_context::RouterGatewayContext,) -> RouterResult<types::AddAccessTokenResult> {Box::pin(access_token::add_access_token(state,diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rsindex 68d00f8d9e..eff22f71a1 100644--- a/crates/router/src/core/payments/flows/psync_flow.rs+++ b/crates/router/src/core/payments/flows/psync_flow.rs@@ -3,14 +3,13 @@ use std::collections::HashMap;use async_trait::async_trait;use common_enums;use hyperswitch_domain_models::payments as domain_payments;-use hyperswitch_interfaces::api::gateway;use super::{ConstructFlowSpecificData, Feature};use crate::{connector::utils::RouterData,core::{errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},- payments::{self, access_token, helpers, transformers, PaymentData},+ payments::{self, access_token, gateway, helpers, transformers, PaymentData},},routes::SessionState,services::{self, api::ConnectorValidation, logger},@@ -175,7 +174,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>connector: &api::ConnectorData,_processor: &domain::Processor,creds_identifier: Option<&str>,- gateway_context: &payments::gateway::context::RouterGatewayContext,+ gateway_context: &gateway::context::RouterGatewayContext,) -> RouterResult<types::AddAccessTokenResult> {let current_flow = Some(hyperswitch_interfaces::api::CurrentFlowInfo::Psync {request_data: Box::new(self.request.clone()),diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rsindex e867e634e2..fc5a6394cf 100644--- a/crates/router/src/core/payments/flows/session_flow.rs+++ b/crates/router/src/core/payments/flows/session_flow.rs@@ -12,7 +12,6 @@ use common_utils::{use error_stack::{Report, ResultExt};#[cfg(feature = "v2")]use hyperswitch_domain_models::payments::PaymentIntentData;-use hyperswitch_interfaces::api::gateway;use hyperswitch_masking::{ExposeInterface, ExposeOptionInterface};use super::{ConstructFlowSpecificData, Feature};@@ -22,7 +21,7 @@ use crate::{configs::dimension_state,errors::{self, ConnectorErrorExt, RouterResult},payments::{- self, access_token, customers,+ self, access_token, customers, gateway,gateway::context as gateway_context,helpers::{self},transformers, PaymentData,@@ -1544,7 +1543,7 @@ wherecall_connector_action: payments::CallConnectorAction,business_profile: &domain::Profile,header_payload: hyperswitch_domain_models::payments::HeaderPayload,- gateway_context: payments::gateway::context::RouterGatewayContext,+ gateway_context: gateway_context::RouterGatewayContext,) -> RouterResult<Self>;}@@ -1746,7 +1745,7 @@ impl RouterDataSession for types::PaymentsSessionRouterData {call_connector_action: payments::CallConnectorAction,business_profile: &domain::Profile,header_payload: hyperswitch_domain_models::payments::HeaderPayload,- gateway_context: payments::gateway::context::RouterGatewayContext,+ gateway_context: gateway_context::RouterGatewayContext,) -> RouterResult<Self> {match connector.get_token {api::GetToken::GpayMetadata => {diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rsindex 48c2e9f4fb..b5c3dedbfa 100644--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs@@ -9,7 +9,7 @@ use hyperswitch_domain_models::{router_flow_types, router_request_types, router_response_types,};use hyperswitch_interfaces::{- api::{self as api_interface, gateway, ConnectorSpecifications},+ api::{self as api_interface, ConnectorSpecifications},consts as interface_consts,};use router_env::logger;@@ -20,7 +20,7 @@ use crate::{errors::{self, ConnectorErrorExt, RouterResult},mandate,payments::{- self, access_token, customers, gateway as payments_gateway,+ self, access_token, customers, gateway, gateway as payments_gateway,gateway::context as gateway_context, helpers, session_token, tokenization,transformers, PaymentData,},diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rsindex b8beb3f780..4cb8cfc68b 100644--- a/crates/router/src/core/payments/gateway.rs+++ b/crates/router/src/core/payments/gateway.rs@@ -25,11 +25,16 @@ use common_enums;use hyperswitch_domain_models::{router_data_v2::PaymentFlowData, router_flow_types::payments};use hyperswitch_interfaces::{api::{gateway, Connector, ConnectorIntegration},+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},+ errors::ConnectorError,};use crate::{- core::{errors::utils::ConnectorErrorExt, payments::gateway::context as gateway_context},+ core::{+ errors::utils::ConnectorErrorExt, payments::gateway::context as gateway_context,+ unified_connector_service::kill_switch,+ },errors::RouterResult,services, types,types::api,@@ -46,6 +51,59 @@ pub static GRANULAR_GATEWAY_SUPPORTED_FLOWS: sync::LazyLock<Vec<&'static str>> =]});+/// Execute a payment gateway and record qualifying request failures on the shadow path.+pub fn execute_payment_gateway<'a, F, ConnectorData, Req, Resp, Context, FlowOutput>(+ state: &'a SessionState,+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,+ router_data: &'a types::RouterData<F, Req, Resp>,+ call_connector_action: common_enums::CallConnectorAction,+ connector_request: Option<services::Request>,+ return_raw_connector_response: Option<bool>,+ context: Context,+) -> impl std::future::Future<Output = common_utils::errors::CustomResult<FlowOutput, ConnectorError>>+ + Send+ + 'a+where+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,+ F: Clone+ + std::fmt::Debug+ + Send+ + Sync+ + 'static+ + gateway::FlowGateway<SessionState, ConnectorData, Req, Resp, Context, FlowOutput>,+ Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,+ Context: gateway::GatewayContext + 'static,+ FlowOutput: Clone + Send + Sync + gateway::GetRouterData<F, Req, Resp> + 'static,+{+ // Keep the gateway result and post-execution counter check out of callers' stack frames.+ Box::pin(async move {+ let execution_path = context.execution_path();+ let result = gateway::execute_payment_gateway(+ state,+ connector_integration,+ router_data,+ call_connector_action,+ connector_request,+ return_raw_connector_response,+ context,+ )+ .await;+ if matches!(+ execution_path,+ common_enums::ExecutionPath::ShadowUnifiedConnectorService+ ) {+ kill_switch::shadow::check_record_failure::<F, Req, Resp, FlowOutput>(+ state,+ &router_data.payment_id,+ &result,+ )+ .await;+ }+ result+ })+}+pub async fn handle_gateway_call<Flow, Req, Resp, ResourceCommonData, FlowOutput>(state: &SessionState,router_data: types::RouterData<Flow, Req, Resp>,@@ -76,7 +134,7 @@ whereResp,> = connector.connector.get_connector_integration();// TODO: Handle gateway_context later- let resp = gateway::execute_payment_gateway(+ let resp = execute_payment_gateway(state,connector_integration,&router_data,diff --git a/crates/router/src/core/payments/session_token.rs b/crates/router/src/core/payments/session_token.rsindex b951bfe037..939aab6d62 100644--- a/crates/router/src/core/payments/session_token.rs+++ b/crates/router/src/core/payments/session_token.rs@@ -2,13 +2,13 @@ use std::fmt::Debug;use common_enums::enums;use error_stack::{report, ResultExt};-use hyperswitch_interfaces::api::{gateway, ConnectorSpecifications};+use hyperswitch_interfaces::api::ConnectorSpecifications;use crate::{core::{errors,errors::utils::ConnectorErrorExt,- payments::{gateway::context as gateway_context, RouterResult},+ payments::{gateway, gateway::context as gateway_context, RouterResult},},logger, routes, services, types,types::{api as api_types, transformers::ForeignFrom},diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 4195bb461a..404732076b 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -23,7 +23,6 @@ use hyperswitch_domain_models::{payment_method_data::{get_applepay_wallet_info, get_googlepay_wallet_info},transformers::ForeignFrom as _,};-use hyperswitch_interfaces::api::gateway;use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use router_env::{instrument, tracing};@@ -39,7 +38,7 @@ use crate::{errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},mandate,payment_methods::{self, cards::PmCards, network_tokenization},- payments::{self, gateway::context as gateway_context},+ payments::{self, gateway, gateway::context as gateway_context},utils::create_encrypted_data,},logger,diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 1a70fb7fc1..ae9fed513e 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -1,5 +1,7 @@#[cfg(feature = "olap")]use strum::IntoEnumIterator;++use crate::core::payouts::gateway as payout_gateway;pub mod access_token;pub mod gateway;#[cfg(feature = "v1")]@@ -41,7 +43,6 @@ use external_services::grpc_client;#[cfg(feature = "olap")]use futures::future::join_all;use hyperswitch_domain_models::{self as domain_models, payment_methods::PaymentMethod};-use hyperswitch_interfaces::api::gateway as payout_gateway;use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};#[cfg(feature = "payout_retry")]use retry::GsmValidation;diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rsindex 451d17ec07..01e1ff5344 100644--- a/crates/router/src/core/payouts/access_token.rs+++ b/crates/router/src/core/payouts/access_token.rs@@ -1,14 +1,14 @@use common_utils::ext_traits::AsyncExt;use error_stack::ResultExt;use hyperswitch_interfaces::{- api::{gateway, ConnectorCommon, ConnectorValidation},+ api::{ConnectorCommon, ConnectorValidation},consts,};use crate::{core::{errors::{self, RouterResult},- payments,+ payments::{self, gateway},payouts::gateway::context as gateway_context,},routes::{metrics, SessionState},diff --git a/crates/router/src/core/payouts/gateway.rs b/crates/router/src/core/payouts/gateway.rsindex 41920a429a..2cc98ee495 100644--- a/crates/router/src/core/payouts/gateway.rs+++ b/crates/router/src/core/payouts/gateway.rs@@ -7,3 +7,64 @@ pub mod quote_gateway;pub mod recipient_account_gateway;pub mod recipient_gateway;pub mod sync_gateway;++use hyperswitch_interfaces::{+ api::gateway,+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},+ errors::ConnectorError,+};++use crate::{core::unified_connector_service::kill_switch, services, types, SessionState};++/// Execute a payout gateway and record qualifying request failures on the shadow path.+pub fn execute_payout_gateway<'a, F, ConnectorData, Req, Resp, Context, FlowOutput>(+ state: &'a SessionState,+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,+ router_data: &'a types::RouterData<F, Req, Resp>,+ call_connector_action: common_enums::CallConnectorAction,+ connector_request: Option<services::Request>,+ return_raw_connector_response: Option<bool>,+ context: Context,+) -> impl std::future::Future<Output = common_utils::errors::CustomResult<FlowOutput, ConnectorError>>+ + Send+ + 'a+where+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,+ F: Clone+ + std::fmt::Debug+ + Send+ + Sync+ + 'static+ + gateway::PayoutFlowGateway<SessionState, ConnectorData, Req, Resp, Context, FlowOutput>,+ Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,+ Context: gateway::GatewayContext + 'static,+ FlowOutput: Clone + Send + Sync + gateway::GetRouterData<F, Req, Resp> + 'static,+{+ // Keep the gateway result and post-execution counter check out of callers' stack frames.+ Box::pin(async move {+ let execution_path = context.execution_path();+ let result = gateway::execute_payout_gateway(+ state,+ connector_integration,+ router_data,+ call_connector_action,+ connector_request,+ return_raw_connector_response,+ context,+ )+ .await;+ if matches!(+ execution_path,+ common_enums::ExecutionPath::ShadowUnifiedConnectorService+ ) {+ kill_switch::shadow::check_record_failure::<F, Req, Resp, FlowOutput>(+ state,+ &router_data.payment_id,+ &result,+ )+ .await;+ }+ result+ })+}diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 9edfe2f665..ba4af6b7e0 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1103,6 +1103,20 @@ where}}+ // Apply the global shadow kill switch before any proxy override.+ if matches!(execution_path, ExecutionPath::ShadowUnifiedConnectorService)+ && kill_switch::shadow::is_kill_switched(state).await+ {+ gateway_system = GatewaySystem::Direct;+ execution_path = ExecutionPath::Direct;+ router_env::logger::warn!(+ payment_id = %router_data.payment_id,+ merchant_id = %merchant_id,+ key = consts::UCS_SHADOW_KILL_SWITCH_REDIS_KEY,+ "Shadow kill switch active; routing to Direct without proxy override"+ );+ }+// Handle proxy configuration for Shadow UCS flowslet session_state = match execution_path {ExecutionPath::ShadowUnifiedConnectorService => {@@ -4072,7 +4086,7 @@ whereif let UnifiedConnectorServiceError::ConnectorError(inner) = error.current_context() {// Fire kill switch for connector errorsif let Ok(flow_name) = get_flow_name::<T>() {- kill_switch::record_failure(+ kill_switch::check_record_failure(state,kill_switch::UcsFailureContext {merchant_id: merchant_id.get_string_repr(),@@ -4113,7 +4127,7 @@ where// Fire kill switch for non-connector UCS errorsmatch get_flow_name::<T>() {Ok(flow_name) => {- kill_switch::record_failure(+ kill_switch::check_record_failure(state,kill_switch::UcsFailureContext {merchant_id: merchant_id.get_string_repr(),@@ -4313,7 +4327,7 @@ whereif let UnifiedConnectorServiceError::ConnectorError(inner) = error.current_context() {// Fire kill switch for connector errorsif let Ok(flow_name) = get_flow_name::<T>() {- kill_switch::record_failure(+ kill_switch::check_record_failure(state,kill_switch::UcsFailureContext {merchant_id: merchant_id.get_string_repr(),@@ -4355,7 +4369,7 @@ where// 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(+ kill_switch::check_record_failure(state,kill_switch::UcsFailureContext {merchant_id: merchant_id.get_string_repr(),diff --git a/crates/router/src/core/unified_connector_service/kill_switch.rs b/crates/router/src/core/unified_connector_service/kill_switch.rsindex 488e041f7a..bae2ed91e1 100644--- a/crates/router/src/core/unified_connector_service/kill_switch.rs+++ b/crates/router/src/core/unified_connector_service/kill_switch.rs@@ -1,9 +1,6 @@-//! Returns a rollout scope to the shadow connector integration when a Unified Connector Service-//! call fails more than a configurable threshold number of times.-//!-//! Failures are counted in Redis via HINCRBY on a hash key scoped to the rollout scope. The read-//! path (`is_kill_switched`) compares the counter against the threshold from the RolloutConfig.-//! When the counter exceeds the threshold, the scope falls back to shadow mode.+//! Shared Redis kill switches for primary UCS calls and shadow proxy traffic.+//! Primary UCS failures divert their rollout scope to shadow; qualifying HS proxy failures+//! divert shadow traffic to Direct. Both use atomic counters with configurable thresholds.use std::str::FromStr;@@ -178,15 +175,24 @@ async fn read_counter(rollout_scope: &str,failure_class: UcsFailureClass,) -> error_stack::Result<u64, storage_impl::errors::RedisError> {- let key: redis_interface::RedisKey = counter_key(rollout_scope).as_str().into();- let count: u64 = state- .store- .get_redis_conn()?- .get_hash_field::<Option<u64>>(&key, failure_class.counter_field())- .await?- .unwrap_or(0);+ read_hash_counter(+ &state.store.get_redis_conn()?,+ &counter_key(rollout_scope),+ failure_class.counter_field(),+ )+ .await+}- Ok(count)+/// Shared counter read for tenant-scoped UCS and global shadow proxy switches.+async fn read_hash_counter(+ conn: &redis_interface::RedisConnectionWithContext,+ key: &str,+ field: &str,+) -> error_stack::Result<u64, storage_impl::errors::RedisError> {+ Ok(conn+ .get_hash_field::<Option<u64>>(&key.into(), field)+ .await?+ .unwrap_or(0))}/// The scope's kill switch settings, resolved once by the gate and carried to the failure@@ -261,7 +267,7 @@ struct TrippableFailure {/// Records a connector decline: UCS answered gRPC OK with a connector 2xx, and the/// connector still refused the payment.///-/// Separate entry point from [`record_failure`] because there is no+/// Separate entry point from [`check_record_failure`] because there is no/// `UnifiedConnectorServiceError` to classify on this path — the refusal arrives as/// `router_data.response` being `Err`. Counts only when the scope sets/// `connector_decline_threshold`.@@ -285,7 +291,7 @@ pub async fn record_decline(/// Records a qualifying UCS failure by incrementing its scope's counter.////// Never returns an error: it runs on an already-failing path and must not fail the request.-pub async fn record_failure(+pub async fn check_record_failure(state: &SessionState,context: UcsFailureContext<'_>,settings: RolloutSettings,@@ -481,24 +487,36 @@ async fn write_counter(rollout_scope: &str,failure_class: UcsFailureClass,) -> error_stack::Result<Vec<usize>, storage_impl::errors::RedisError> {- let conn = state.store.get_redis_conn()?;- let key: redis_interface::RedisKey = counter_key(rollout_scope).as_str().into();+ write_hash_counter(+ &state.store.get_redis_conn()?,+ &counter_key(rollout_scope),+ failure_class.counter_field(),+ consts::UCS_KILL_SWITCH_TTL_IN_SECONDS,+ )+ .await+}+/// Atomic HINCRBY, with a best-effort expiry refresh shared by both switches.+async fn write_hash_counter(+ conn: &redis_interface::RedisConnectionWithContext,+ key: &str,+ field: &str,+ ttl_in_seconds: i64,+) -> error_stack::Result<Vec<usize>, storage_impl::errors::RedisError> {+ let redis_key = key.into();let result = conn- .increment_fields_in_hash(&key, &[(failure_class.counter_field(), 1)])+ .increment_fields_in_hash(&redis_key, &[(field, 1)]).await?;-- conn.set_expiry(&key, consts::UCS_KILL_SWITCH_TTL_IN_SECONDS)+ conn.set_expiry(&redis_key, ttl_in_seconds).await.inspect_err(|error| {logger::warn!(?error,- rollout_scope = %rollout_scope,+ key,"ucs_kill_switch: failed to refresh counter TTL");}).ok();-Ok(result)}@@ -507,7 +525,7 @@ async fn write_counter(pub struct KillSwitchStatusResponse {pub rollout_scope: String,pub counter: u64,- /// `None` when no `RolloutConfig` exists for this scope — falls back to trip-on-first-failure.+ /// Shadow uses its configured threshold. For primary UCS, `None` means no rollout config.pub threshold: Option<u64>,/// Connector declines, counted separately from `counter` and measured against/// `connector_decline_threshold`.@@ -524,13 +542,18 @@ impl common_utils::events::ApiEventMetric for KillSwitchStatusResponse {}/// Clears the counter, returning the scope to whatever its rollout config says.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()+ let (conn, key) = if listed_key == consts::UCS_SHADOW_KILL_SWITCH_REDIS_KEY {+ // The MITM proxy and its shadow counter are shared across tenants. Read,+ // increment and reset that counter through the same global Redis namespace.+ (state.global_store.get_redis_conn(), listed_key.clone())+ } else {+ // Primary UCS counters belong to a tenant's merchant rollout scope.+ (state.store.get_redis_conn(), counter_key(rollout_scope))+ };+ let reply = conn.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get a redis connection to clear the UCS kill switch")?- .delete_key(&counter_key(rollout_scope).as_str().into())+ .delete_key(&key.as_str().into()).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to delete the UCS kill switch counter")?;@@ -558,6 +581,24 @@ pub async fn trip_status(state: SessionState,key_or_scope: String,) -> errors::RouterResponse<KillSwitchStatusResponse> {+ if key_or_scope == consts::UCS_SHADOW_KILL_SWITCH_REDIS_KEY {+ let counter = shadow::read_counter(&state)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to read the shadow kill switch counter")?;+ let threshold = shadow::threshold(&state);+ return Ok(crate::services::ApplicationResponse::Json(+ KillSwitchStatusResponse {+ rollout_scope: key_or_scope,+ counter,+ threshold: Some(threshold),+ decline_counter: 0,+ connector_decline_threshold: None,+ tripped: exceeds_threshold(counter, threshold),+ },+ ));+ }+let rollout_scope = rollout_scope_in(&key_or_scope);let counter_value: u64 =@@ -825,3 +866,336 @@ mod tests {assert_eq!(unique.len(), tags.len());}}++/// Disable shadow proxying after qualifying request failures reach a shared threshold.+/// The proxy is shared across tenants, so its counter uses `global_store` consistently+/// for increments, enforcement, status and reset. Primary UCS counters use tenant `store`.+pub mod shadow {+ use std::{error::Error, io::ErrorKind};++ use common_enums::ApiClientError;+ use hyperswitch_domain_models::router_data::ErrorResponse;+ use hyperswitch_interfaces::{api::gateway::GetRouterData, errors::ConnectorError};+ use router_env::logger;++ use super::{exceeds_threshold, read_hash_counter, write_hash_counter, COUNTER_FIELD};+ use crate::{+ consts::{+ UCS_SHADOW_KILL_SWITCH_REDIS_KEY as COUNTER_KEY, UCS_SHADOW_KILL_SWITCH_TTL_IN_SECONDS,+ },+ routes::SessionState,+ };++ /// Classification is separate from the explicit counter eligibility policy.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display)]+ #[strum(serialize_all = "snake_case")]+ enum ShadowFailureReason {+ RequestTimeout,+ DnsFailure,+ ConnectionRefused,+ ProxyAuthenticationRequired,+ Ignored,+ }++ impl ShadowFailureReason {+ fn should_increment_counter(self) -> bool {+ match self {+ Self::RequestTimeout+ | Self::DnsFailure+ | Self::ConnectionRefused+ | Self::ProxyAuthenticationRequired => true,+ Self::Ignored => false,+ }+ }+ }++ pub(super) async fn read_counter(+ state: &SessionState,+ ) -> error_stack::Result<u64, storage_impl::errors::RedisError> {+ read_hash_counter(+ &state.global_store.get_redis_conn()?,+ COUNTER_KEY,+ COUNTER_FIELD,+ )+ .await+ }++ pub(super) fn threshold(state: &SessionState) -> u64 {+ state+ .conf+ .comparison_service+ .as_ref()+ .map_or(1, |config| config.shadow_kill_switch_threshold)+ }++ fn request_failure_reason(error: &error_stack::Report<ConnectorError>) -> ShadowFailureReason {+ let client_timeout = error+ .downcast_ref::<ApiClientError>()+ .is_some_and(ApiClientError::is_upstream_timeout);+ let connector_timeout = error.current_context().is_connector_timeout();+ if client_timeout || connector_timeout {+ ShadowFailureReason::RequestTimeout+ } else if error.downcast_ref::<http::StatusCode>()+ == Some(&http::StatusCode::PROXY_AUTHENTICATION_REQUIRED)+ {+ ShadowFailureReason::ProxyAuthenticationRequired+ } else {+ match error.downcast_ref::<reqwest::Error>() {+ Some(error) if error.is_timeout() => ShadowFailureReason::RequestTimeout,+ Some(error) if error.is_connect() => connection_failure_reason(error),+ _ => ShadowFailureReason::Ignored,+ }+ }+ }++ fn connection_failure_reason(error: &reqwest::Error) -> ShadowFailureReason {+ std::iter::successors(error.source(), |source| (*source).source())+ .map(|cause| {+ let connection_refused = cause+ .downcast_ref::<std::io::Error>()+ .is_some_and(|error| error.kind() == ErrorKind::ConnectionRefused);+ // Hyper 0.14's private DNS error type exposes this fixed prefix.+ match cause.to_string().as_str() {+ _ if connection_refused => ShadowFailureReason::ConnectionRefused,+ "proxy authentication required" => {+ ShadowFailureReason::ProxyAuthenticationRequired+ }+ message if message == "dns error" || message.starts_with("dns error:") => {+ ShadowFailureReason::DnsFailure+ }+ _ => ShadowFailureReason::Ignored,+ }+ })+ .find(|reason| *reason != ShadowFailureReason::Ignored)+ .unwrap_or(ShadowFailureReason::Ignored)+ }++ fn response_failure_reason(error: &ErrorResponse) -> ShadowFailureReason {+ match error.status_code {+ 407 => ShadowFailureReason::ProxyAuthenticationRequired,+ 504 if error.code == hyperswitch_interfaces::consts::REQUEST_TIMEOUT_ERROR_CODE+ && error.message+ == hyperswitch_interfaces::consts::REQUEST_TIMEOUT_ERROR_MESSAGE =>+ {+ ShadowFailureReason::RequestTimeout+ }+ _ => ShadowFailureReason::Ignored,+ }+ }++ /// Called only on the shadow path; classify the original request result and record+ /// timeouts, DNS failures, connection refused or explicit proxy authentication failures.+ /// These errors do not establish whether the proxy or upstream connector failed.+ /// Body/decoding errors and ordinary connector 5xx responses do not count.+ /// Redis commands use the application's existing configured timeout.+ pub async fn check_record_failure<F, Req, Resp, Output>(+ state: &SessionState,+ payment_id: &str,+ result: &common_utils::errors::CustomResult<Output, ConnectorError>,+ ) where+ Output: GetRouterData<F, Req, Resp>,+ {+ let reason = match result {+ Err(error) => request_failure_reason(error),+ Ok(output) => {+ let router_data = output.get_router_data();+ if router_data.connector_http_status_code == Some(407) {+ ShadowFailureReason::ProxyAuthenticationRequired+ } else {+ router_data+ .response+ .as_ref()+ .err()+ .map_or(ShadowFailureReason::Ignored, response_failure_reason)+ }+ }+ };+ if reason.should_increment_counter() {+ let write = async {+ let conn = state.global_store.get_redis_conn()?;+ write_hash_counter(+ &conn,+ COUNTER_KEY,+ COUNTER_FIELD,+ UCS_SHADOW_KILL_SWITCH_TTL_IN_SECONDS,+ )+ .await+ }+ .await;+ match write {+ Ok(counts) => {+ let count = counts.first().and_then(|count| u64::try_from(*count).ok());+ logger::warn!(+ payment_id,+ request_id = ?state.request_id,+ count = ?count,+ reason = %reason,+ "SHADOW_KILL_SWITCH_COUNTER_INCREMENTED"+ );++ let configured_threshold = threshold(state);+ // The atomic Redis increment returns the threshold value to only one+ // request, so concurrent failures do not repeat the trip event.+ if let Some(count) = count.filter(|count| *count == configured_threshold) {+ logger::warn!(+ key = COUNTER_KEY,+ payment_id,+ request_id = ?state.request_id,+ count,+ threshold = configured_threshold,+ reason = %reason,+ "SHADOW_KILL_SWITCH_TRIPPED"+ );+ }+ }+ Err(error) => logger::warn!(+ payment_id,+ request_id = ?state.request_id,+ ?error,+ "Shadow kill switch counter increment failed"+ ),+ }+ }+ }++ /// Read only for a resultant shadow path, before changing any proxy settings.+ /// An unreadable Redis counter routes shadow to Direct.+ pub async fn is_kill_switched(state: &SessionState) -> bool {+ match read_counter(state).await {+ Ok(count) => exceeds_threshold(count, threshold(state)),+ Err(error) => {+ logger::warn!(+ ?error,+ key = COUNTER_KEY,+ "Shadow kill switch counter unavailable; routing to Direct"+ );+ true+ }+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn proxy_authentication_and_request_timeout_responses_count() {+ let response = ErrorResponse {+ status_code: 407,+ ..Default::default()+ };+ assert_eq!(+ response_failure_reason(&response),+ ShadowFailureReason::ProxyAuthenticationRequired+ );+ assert!(response_failure_reason(&response).should_increment_counter());+ let response = ErrorResponse {+ status_code: 504,+ code: hyperswitch_interfaces::consts::REQUEST_TIMEOUT_ERROR_CODE.to_owned(),+ message: hyperswitch_interfaces::consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_owned(),+ ..Default::default()+ };+ assert_eq!(+ response_failure_reason(&response),+ ShadowFailureReason::RequestTimeout+ );+ }++ #[test]+ fn ordinary_upstream_5xx_responses_do_not_count() {+ for status_code in [500, 502, 503, 504] {+ let response = ErrorResponse {+ status_code,+ ..Default::default()+ };+ let reason = response_failure_reason(&response);+ assert_eq!(reason, ShadowFailureReason::Ignored);+ assert!(!reason.should_increment_counter());+ }+ }++ #[test]+ fn typed_request_timeouts_count_directly() {+ let error = error_stack::Report::new(ApiClientError::RequestTimeoutReceived)+ .change_context(ConnectorError::ProcessingStepFailed(None));+ assert_eq!(+ request_failure_reason(&error),+ ShadowFailureReason::RequestTimeout+ );+ let error = error_stack::Report::new(ConnectorError::RequestTimeoutReceived);+ assert_eq!(+ request_failure_reason(&error),+ ShadowFailureReason::RequestTimeout+ );+ assert!(request_failure_reason(&error).should_increment_counter());+ assert_eq!(+ request_failure_reason(&error).to_string(),+ "request_timeout"+ );+ }++ #[test]+ fn arbitrary_io_and_connection_closed_errors_do_not_count() {+ let error = error_stack::Report::new(std::io::Error::from(ErrorKind::ConnectionReset))+ .change_context(ConnectorError::ProcessingStepFailed(None));+ let reason = request_failure_reason(&error);+ assert_eq!(reason, ShadowFailureReason::Ignored);+ assert!(!reason.should_increment_counter());+ let error = error_stack::Report::new(ApiClientError::ConnectionClosedIncompleteMessage)+ .change_context(ConnectorError::ProcessingStepFailed(None));+ assert_eq!(request_failure_reason(&error), ShadowFailureReason::Ignored);+ }++ #[tokio::test]+ async fn connection_refused_counts_from_the_original_request() {+ // Reserve the port without listening, so another test cannot claim it.+ let socket = tokio::net::TcpSocket::new_v4().expect("socket");+ socket+ .bind("127.0.0.1:0".parse().expect("address"))+ .expect("bind");+ let error = reqwest::Client::builder()+ .no_proxy()+ .build()+ .expect("client")+ .get(format!("http://{}/", socket.local_addr().expect("address")))+ .send()+ .await+ .expect_err("connection refused");+ let error = error_stack::Report::new(error)+ .change_context(ConnectorError::ProcessingStepFailed(None));+ assert_eq!(+ request_failure_reason(&error),+ ShadowFailureReason::ConnectionRefused+ );+ assert!(request_failure_reason(&error).should_increment_counter());+ }++ #[tokio::test]+ async fn request_timeout_counts_without_an_endpoint_probe() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind");+ let address = listener.local_addr().expect("address");+ let server = tokio::spawn(async move {+ let (_connection, _) = listener.accept().await.expect("accept");+ std::future::pending::<()>().await;+ });+ let error = reqwest::Client::builder()+ .no_proxy()+ .timeout(std::time::Duration::from_millis(100))+ .build()+ .expect("client")+ .get(format!("http://{address}/"))+ .send()+ .await+ .expect_err("request timeout");+ let error = error_stack::Report::new(error)+ .change_context(ConnectorError::ProcessingStepFailed(None));+ assert_eq!(+ request_failure_reason(&error),+ ShadowFailureReason::RequestTimeout+ );+ server.abort();+ }+ }+}diff --git a/crates/router/src/routes/unified_connector_service.rs b/crates/router/src/routes/unified_connector_service.rsindex d2cbfd77ed..800da96c1b 100644--- a/crates/router/src/routes/unified_connector_service.rs+++ b/crates/router/src/routes/unified_connector_service.rs@@ -10,6 +10,7 @@ use crate::{/// 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.+/// Use `ucs_shadow_killed` to inspect the global shadow counter and its configured threshold.#[instrument(skip_all, fields(flow = ?Flow::UnifiedConnectorServiceKillSwitchStatus))]pub async fn kill_switch_status(state: web::Data<AppState>,@@ -31,7 +32,7 @@ pub async fn kill_switch_status(}/// Clears a UCS kill switch trip, returning the scope to whatever its rollout config says.-/// Takes the same `scope` as the status endpoint.+/// Accepts a primary UCS rollout scope or its Redis key, or `ucs_shadow_killed` for shadow.#[instrument(skip_all, fields(flow = ?Flow::UnifiedConnectorServiceKillSwitchReset))]pub async fn reset_kill_switch(state: web::Data<AppState>,