Skip to content

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

fix(ucs): fire kill switch on connector errors in Ok(RouterData) (#13683)

Amitsingh Tanwar3aae4545e2bc
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 7ad43639a6..bda30a33ad 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -365,10 +365,6 @@ pub const UCS_ROLLOUT_CONFIG_NOT_CONFIGURED: &str = "not_configured";
// UCS feature enabled config
pub 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";
diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs
index 4bf812ca4f..5ae13a9bcb 100644
--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs
+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs
@@ -463,6 +463,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
headers_builder,
unified_connector_service_execution_mode,
|mut router_data, payment_authorize_request, grpc_headers| async move {
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper`.
let response = Box::pin(client
.payment_authorize(
payment_authorize_request,
@@ -470,7 +471,6 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
grpc_headers,
))
.await
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authorize_response = response.into_inner();
@@ -480,7 +480,6 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
payment_authorize_response.clone(),
router_data.status,
)
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = match ucs_data.router_data_response {
@@ -579,6 +578,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
headers_builder,
unified_connector_service_execution_mode,
|mut router_data, payment_authorize_request, grpc_headers| async move {
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper`.
let response = Box::pin(client
.payment_authorize(
payment_authorize_request,
@@ -586,7 +586,6 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
grpc_headers,
))
.await
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authorize_response = response.into_inner();
@@ -596,7 +595,6 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
payment_authorize_response.clone(),
router_data.status,
)
- .change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = match ucs_data.router_data_response {
diff --git a/crates/router/src/core/payments/gateway/access_token_gateway.rs b/crates/router/src/core/payments/gateway/access_token_gateway.rs
index e1eb72b1c8..564bead838 100644
--- a/crates/router/src/core/payments/gateway/access_token_gateway.rs
+++ b/crates/router/src/core/payments/gateway/access_token_gateway.rs
@@ -12,7 +12,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -176,25 +175,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for access token (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::MerchantAuthenticationServiceCreateServerAuthenticationTokenResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to create access token"));
}
};
diff --git a/crates/router/src/core/payments/gateway/authorize_gateway.rs b/crates/router/src/core/payments/gateway/authorize_gateway.rs
index cc1bdc88e7..e0c106d207 100644
--- a/crates/router/src/core/payments/gateway/authorize_gateway.rs
+++ b/crates/router/src/core/payments/gateway/authorize_gateway.rs
@@ -144,34 +144,11 @@ where
.await
{
Ok(resp) => resp,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- // Check if this is a connector error (4xx/5xx from connector via UCS)
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- let (code, message, status_code, connector) = (
- &inner.code,
- &inner.message,
- inner.status_code,
- &inner.connector,
- );
- logger::debug!(
- "Connector error via UCS for recurring charge (connector {}, status {}): {} - {}",
- connector,
- status_code,
- code,
- message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::RecurringPaymentServiceChargeResponse::default(),
- ));
- }
- // Propagate as Err for proper HTTP error handling
- return Err(report.attach_printable("Failed to charge recurring payment"));
+ return Err(
+ report.attach_printable("Failed to charge recurring payment")
+ );
}
};
@@ -250,37 +227,8 @@ where
.await
{
Ok(resp) => resp,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- // Check if this is a connector error (4xx/5xx from connector via UCS)
- // If so, set it as router_data.response = Err(ErrorResponse) and return Ok
- // This matches how direct connector errors are handled
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- let (code, message, status_code, connector) = (
- &inner.code,
- &inner.message,
- inner.status_code,
- &inner.connector,
- );
- logger::debug!(
- "Connector error via UCS (connector {}, status {}): {} - {}",
- connector,
- status_code,
- code,
- message
- );
- router_data.response = Err(inner.as_ref().into());
- // Return Ok with router_data containing the error response
- // This ensures the connector error flows through the normal
- // response handling path (same as direct connector errors)
- router_data.connector_http_status_code = Some(status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceAuthorizeResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to authorize payment"));
}
};
diff --git a/crates/router/src/core/payments/gateway/cancel_gateway.rs b/crates/router/src/core/payments/gateway/cancel_gateway.rs
index c807e5f0ee..e0d0cd5bac 100644
--- a/crates/router/src/core/payments/gateway/cancel_gateway.rs
+++ b/crates/router/src/core/payments/gateway/cancel_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -120,31 +119,8 @@ where
.await
{
Ok(resp) => resp,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- let (code, message, status_code, connector) = (
- &inner.code,
- &inner.message,
- inner.status_code,
- &inner.connector,
- );
- logger::debug!(
- "Connector error via UCS for void (connector {}, status {}): {} - {}",
- connector,
- status_code,
- code,
- message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceVoidResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to Void payment"));
}
};
diff --git a/crates/router/src/core/payments/gateway/capture_gateway.rs b/crates/router/src/core/payments/gateway/capture_gateway.rs
index c0fe74cc4d..8747261014 100644
--- a/crates/router/src/core/payments/gateway/capture_gateway.rs
+++ b/crates/router/src/core/payments/gateway/capture_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -122,31 +121,8 @@ where
.await
{
Ok(resp) => resp,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- let (code, message, status_code, connector) = (
- &inner.code,
- &inner.message,
- inner.status_code,
- &inner.connector,
- );
- logger::debug!(
- "Connector error via UCS for capture (connector {}, status {}): {} - {}",
- connector,
- status_code,
- code,
- message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceCaptureResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to capture payment"));
}
};
diff --git a/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs
index e11f80a6ef..13c46331be 100644
--- a/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs
+++ b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use hyperswitch_masking::ExposeInterface as UcsMaskingExposeInterface;
use unified_connector_service_client::payments as payments_grpc;
@@ -126,25 +125,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for complete authorize (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceAuthorizeResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to get payment"));
}
};
diff --git a/crates/router/src/core/payments/gateway/create_customer_gateway.rs b/crates/router/src/core/payments/gateway/create_customer_gateway.rs
index c060bddc83..2f9740d0c9 100644
--- a/crates/router/src/core/payments/gateway/create_customer_gateway.rs
+++ b/crates/router/src/core/payments/gateway/create_customer_gateway.rs
@@ -12,7 +12,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -134,25 +133,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for create connector customer (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::CustomerServiceCreateResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to create connector customer"));
}
};
diff --git a/crates/router/src/core/payments/gateway/create_order_gateway.rs b/crates/router/src/core/payments/gateway/create_order_gateway.rs
index a3c6902f55..be09fcfd67 100644
--- a/crates/router/src/core/payments/gateway/create_order_gateway.rs
+++ b/crates/router/src/core/payments/gateway/create_order_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -126,25 +125,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for create order (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceCreateOrderResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to create order"));
}
};
diff --git a/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs
index a3cd03ac79..6efbdaace5 100644
--- a/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs
+++ b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -137,25 +136,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for incremental authorization (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceIncrementalAuthorizationResponse::default(),
- ));
- }
return Err(report.attach_printable(
"Failed to in incremental authorize payment",
));
diff --git a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
index 34b7dc2107..6e5aaeadaf 100644
--- a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
+++ b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -131,25 +130,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for payment method tokenization (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentMethodServiceTokenizeResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to Tokenize payment method"));
}
};
diff --git a/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs b/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs
index 980083756e..b17f5fe58f 100644
--- a/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs
+++ b/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -128,25 +127,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for pre-authorize void (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceVoidResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to Cancel payment"));
}
};
diff --git a/crates/router/src/core/payments/gateway/psync_gateway.rs b/crates/router/src/core/payments/gateway/psync_gateway.rs
index 5157c6dbc8..4074477aa0 100644
--- a/crates/router/src/core/payments/gateway/psync_gateway.rs
+++ b/crates/router/src/core/payments/gateway/psync_gateway.rs
@@ -12,7 +12,6 @@ use hyperswitch_interfaces::{
unified_connector_service::{
get_payments_response_from_ucs_webhook_content,
handle_unified_connector_service_response_for_payment_get,
- transformers::UnifiedConnectorServiceError,
},
};
use hyperswitch_masking::ExposeInterface as UcsMaskingExposeInterface;
@@ -205,31 +204,8 @@ where
.await
{
Ok(resp) => resp,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- let (code, message, status_code, connector) = (
- &inner.code,
- &inner.message,
- inner.status_code,
- &inner.connector,
- );
- logger::debug!(
- "Connector error via UCS for psync (connector {}, status {}): {} - {}",
- connector,
- status_code,
- code,
- message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceGetResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to get payment"));
}
};
@@ -273,10 +249,10 @@ where
Some(MinorUnit::new(captured_amount));
}
if return_raw_connector_response.unwrap_or(false) {
- router_data.raw_connector_response = payment_get_response
- .raw_connector_response
- .clone()
- .map(|raw_connector_response| raw_connector_response.expose().into());
+ router_data.raw_connector_response =
+ payment_get_response.raw_connector_response.clone().map(
+ |raw_connector_response| raw_connector_response.expose().into(),
+ );
}
router_data.connector_http_status_code = Some(status_code);
router_data.sender_payment_instrument_id =
diff --git a/crates/router/src/core/payments/gateway/session_gateway.rs b/crates/router/src/core/payments/gateway/session_gateway.rs
index 3c53a7d0b2..2ad7c01996 100644
--- a/crates/router/src/core/payments/gateway/session_gateway.rs
+++ b/crates/router/src/core/payments/gateway/session_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -127,25 +126,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for sdk session token (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::MerchantAuthenticationServiceCreateClientAuthenticationTokenResponse::default(),
- ));
- }
return Err(
report.attach_printable("Failed to create SDK session token")
);
diff --git a/crates/router/src/core/payments/gateway/session_token_gateway.rs b/crates/router/src/core/payments/gateway/session_token_gateway.rs
index 6294e325a5..d041ee4478 100644
--- a/crates/router/src/core/payments/gateway/session_token_gateway.rs
+++ b/crates/router/src/core/payments/gateway/session_token_gateway.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -130,25 +129,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for session token (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::MerchantAuthenticationServiceCreateServerSessionAuthenticationTokenResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to create session token"));
}
};
diff --git a/crates/router/src/core/payments/gateway/setup_mandate.rs b/crates/router/src/core/payments/gateway/setup_mandate.rs
index 4c299a6fb6..daf5de1a25 100644
--- a/crates/router/src/core/payments/gateway/setup_mandate.rs
+++ b/crates/router/src/core/payments/gateway/setup_mandate.rs
@@ -9,7 +9,6 @@ use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
- unified_connector_service::transformers::UnifiedConnectorServiceError,
};
use unified_connector_service_client::payments as payments_grpc;
@@ -124,25 +123,8 @@ where
.await
{
Ok(response) => response,
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.
Err(report) => {
- if let UnifiedConnectorServiceError::ConnectorError(inner) =
- report.current_context()
- {
- logger::debug!(
- "Connector error via UCS for setup mandate (connector {}, status {}): {} - {}",
- inner.connector,
- inner.status_code,
- inner.code,
- inner.message
- );
- router_data.response = Err(inner.as_ref().into());
- router_data.connector_http_status_code = Some(inner.status_code);
- return Ok((
- router_data,
- (),
- payments_grpc::PaymentServiceSetupRecurringResponse::default(),
- ));
- }
return Err(report.attach_printable("Failed to setup recurring payment"));
}
};
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 926165cf49..29ed3da50b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2527,6 +2527,18 @@ pub struct RolloutConfig {
pub http_url: Option<String>,
pub https_url: Option<String>,
pub execution_mode: ExecutionMode,
+ #[serde(default = "default_kill_switch_enabled")]
+ pub kill_switch_enabled: bool,
+ #[serde(default = "default_kill_switch_threshold")]
+ pub kill_switch_threshold: u64,
+}
+
+fn default_kill_switch_enabled() -> bool {
+ false
+}
+
+fn default_kill_switch_threshold() -> u64 {
+ 1
}
#[serde_as]
@@ -2546,6 +2558,8 @@ impl Default for RolloutConfig {
http_url: None,
https_url: None,
execution_mode: ExecutionMode::NotApplicable,
+ kill_switch_enabled: false,
+ kill_switch_threshold: 1,
}
}
}
@@ -2558,6 +2572,8 @@ pub struct RolloutExecutionResult {
pub should_execute: bool,
pub proxy_override: Option<ProxyOverride>,
pub execution_mode: ExecutionMode,
+ pub kill_switch_enabled: bool,
+ pub kill_switch_threshold: u64,
}
impl Default for RolloutExecutionResult {
@@ -2566,6 +2582,8 @@ impl Default for RolloutExecutionResult {
should_execute: false,
proxy_override: None,
execution_mode: ExecutionMode::NotApplicable,
+ kill_switch_enabled: false,
+ kill_switch_threshold: 1,
}
}
}
@@ -2653,6 +2671,8 @@ impl From<RolloutConfig> for RolloutExecutionResult {
should_execute: true,
proxy_override,
execution_mode: config.execution_mode,
+ kill_switch_enabled: config.kill_switch_enabled,
+ kill_switch_threshold: config.kill_switch_threshold,
}
}
false => {
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 4a485418c2..7cc18c3506 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -407,8 +407,8 @@ where
}
};
- // Kill switch: a scope that already failed deterministically serves from the direct
- // integration regardless of what its rollout config says.
+ // Kill switch: a scope whose failure counter exceeds the configured threshold 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
@@ -425,12 +425,19 @@ where
router_data.payment_method_type,
);
- if Box::pin(kill_switch::is_tripped(state, &rollout_scope)).await {
+ if Box::pin(kill_switch::is_kill_switched(
+ state,
+ &rollout_scope,
+ rollout_result.kill_switch_enabled,
+ rollout_result.kill_switch_threshold,
+ ))
+ .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"
+ "UCS kill switch counter exceeds threshold for this scope, routing to shadow"
);
gateway_system = GatewaySystem::Direct;
execution_path = ExecutionPath::ShadowUnifiedConnectorService;
@@ -2979,14 +2986,19 @@ where
Resp: std::fmt::Debug + Clone + Send + Sync + 'static,
GrpcReq: serde::Serialize,
GrpcResp: serde::Serialize,
+ FlowOutput: Default,
F: FnOnce(
RouterData<T, Req, Resp>,
GrpcReq,
external_services::grpc_client::GrpcHeadersUcs,
) -> Fut
+ Send,
- Fut: std::future::Future<Output = RouterResult<(RouterData<T, Req, Resp>, FlowOutput, GrpcResp)>>
- + Send,
+ Fut: std::future::Future<
+ Output = CustomResult<
+ (RouterData<T, Req, Resp>, FlowOutput, GrpcResp),
+ UnifiedConnectorServiceError,
+ >,
+ > + Send,
{
tracing::Span::current().record("connector_name", &router_data.connector);
tracing::Span::current().record("flow_type", std::any::type_name::<T>());
@@ -2999,6 +3011,11 @@ where
let 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;
+ // Clone router_data before handler consumes it, so we can use it if the handler
+ // returns a ConnectorError (which we convert to Ok(router_data) with Err(ErrorResponse))
+ let router_data_clone = router_data.clone();
let grpc_header = grpc_header_builder.build();
// Log the actual gRPC request with masking
let grpc_request_body = hyperswitch_masking::masked_serialize(&grpc_request)
@@ -3020,8 +3037,9 @@ where
);
// Execute UCS function and measure timing
+ // Box::pin the handler to reduce the monomorphized future size and prevent stack overflow
let start_time = Instant::now();
- let result = handler(router_data, grpc_request, grpc_header).await;
+ let result = Box::pin(handler(router_data, grpc_request, grpc_header)).await;
let external_latency = start_time.elapsed().as_millis();
// Create and emit connector event after UCS call
@@ -3044,21 +3062,86 @@ where
)
}
Err(error) => {
- // Update error metrics for UCS calls
- crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
- 1,
- router_env::metric_attributes!(("connector", connector_name.clone(),)),
- );
+ // Check if this is a connector error (4xx/5xx from connector via UCS).
+ // Convert it to Ok(router_data) with response = Err(ErrorResponse) so the
+ // caller sees a proper error response instead of a raw UCS error.
+ if let UnifiedConnectorServiceError::ConnectorError(inner) = error.current_context() {
+ // Fire kill switch for connector errors
+ if let Ok(flow_name) = get_flow_name::<T>() {
+ 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;
+ }
- let error_body = serde_json::json!({
- "error": error.to_string(),
- "error_type": "ucs_call_failed"
- });
- (
- error.current_context().status_code().as_u16(),
- Some(error_body),
- Err(error),
- )
+ let status_code = inner.status_code;
+ let mut router_data = router_data_clone;
+ router_data.response = Err(inner.as_ref().into());
+ router_data.connector_http_status_code = Some(status_code);
+
+ let error_body = serde_json::json!({
+ "error": error.to_string(),
+ "error_type": "connector_error"
+ });
+
+ (
+ status_code,
+ Some(error_body),
+ Ok((router_data, FlowOutput::default())),
+ )
+ } else {
+ // Update error metrics for UCS calls
+ crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
+ 1,
+ router_env::metric_attributes!(("connector", connector_name.clone(),)),
+ );
+
+ // Fire kill switch for non-connector UCS errors
+ 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;
+ }
+ 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"
+ });
+ let api_error: errors::ApiErrorResponse = error.current_context().switch();
+ (
+ api_error.status_code().as_u16(),
+ Some(error_body),
+ Err(error.change_context(api_error)),
+ )
+ }
}
};
@@ -3110,6 +3193,7 @@ where
external_services::grpc_client::GrpcHeadersUcs,
) -> Fut
+ Send,
+ FlowOutput: Default,
Fut: std::future::Future<
Output = CustomResult<
(RouterData<T, Req, Resp>, FlowOutput, GrpcResp),
@@ -3150,9 +3234,14 @@ where
),
);
+ // Clone router_data before handler consumes it, so we can use it if the handler
+ // returns a ConnectorError (which we convert to Ok(router_data) with Err(ErrorResponse))
+ let router_data_clone = router_data.clone();
+
// Execute UCS function and measure timing
+ // Box::pin the handler to reduce the monomorphized future size and prevent stack overflow
let start_time = Instant::now();
- let result = handler(router_data, grpc_request, grpc_header).await;
+ let result = Box::pin(handler(router_data, grpc_request, grpc_header)).await;
let external_latency = start_time.elapsed().as_millis();
// Create and emit connector event after UCS call
@@ -3175,16 +3264,12 @@ where
)
}
Err(error) => {
- // Update error metrics for UCS calls
- crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
- 1,
- router_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) => {
+ // Check if this is a connector error (4xx/5xx from connector via UCS).
+ // Convert it to Ok(router_data) with response = Err(ErrorResponse) so the
+ // caller sees a proper error response instead of a raw UCS error.
+ if let UnifiedConnectorServiceError::ConnectorError(inner) = error.current_context() {
+ // Fire kill switch for connector errors
+ if let Ok(flow_name) = get_flow_name::<T>() {
kill_switch::record_failure(
state,
kill_switch::UcsFailureContext {
@@ -3200,24 +3285,67 @@ where
)
.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"
- });
- (
- error.current_context().http_status(),
- Some(error_body),
- Err(error),
- )
+ let status_code = inner.status_code;
+ let mut router_data = router_data_clone;
+ router_data.response = Err(inner.as_ref().into());
+ router_data.connector_http_status_code = Some(status_code);
+
+ let error_body = serde_json::json!({
+ "error": error.to_string(),
+ "error_type": "connector_error"
+ });
+
+ (
+ status_code,
+ Some(error_body),
+ Ok((router_data, FlowOutput::default())),
+ )
+ } else {
+ // Update error metrics for UCS calls
+ crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
+ 1,
+ router_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"
+ });
+ (
+ error.current_context().http_status(),
+ Some(error_body),
+ Err(error),
+ )
+ }
}
};
@@ -3381,14 +3509,6 @@ 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 wrapper
Box::pin(ucs_logging_wrapper(
router_data,
@@ -3398,67 +3518,11 @@ pub async fn call_unified_connector_service_for_refund_execute(
execution_mode,
|mut router_data, grpc_request, grpc_headers| async move {
// Call UCS payment_refund method
- let response = match ucs_client
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper`.
+ let response = ucs_client
.payment_refund(grpc_request, connector_auth_metadata, grpc_headers)
.await
- {
- 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()
- {
- let (code, message, status_code, reason, connector,
- network_decline_code, network_advice_code, network_error_message) = (
- &inner.code, &inner.message, inner.status_code, &inner.reason,
- &inner.connector, &inner.network_decline_code,
- &inner.network_advice_code, &inner.network_error_message,
- );
- logger::info!(
- "Connector error via UCS for refund execute (connector {}, status {}): {} - {}",
- connector,
- status_code,
- code,
- message
- );
- router_data.response = Err(ErrorResponse {
- code: code.clone(),
- message: message.clone(),
- reason: reason.clone(),
- status_code,
- attempt_status: None,
- connector_transaction_id: inner.connector_transaction_id.clone(),
- connector_response_reference_id: None,
- network_decline_code: network_decline_code.clone(),
- network_advice_code: network_advice_code.clone(),
- network_error_message: network_error_message.clone(),
- connector_metadata: None,
- });
- router_data.connector_http_status_code = Some(status_code);
- return Ok((router_data, (), payments_grpc::RefundResponse::default()));
- }
- let api_error = report.current_context().switch();
- return Err(report
- .change_context(api_error)
- .attach_printable("UCS refund execution failed"));
- }
- };
+ .attach_printable("UCS refund execution failed")?;
let grpc_response = response.into_inner();
@@ -3468,7 +3532,6 @@ pub async fn call_unified_connector_service_for_refund_execute(
grpc_response.clone(),
prev_refund_status,
)
- .change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to transform UCS refund response")?;
router_data.response = refund_response_data;
@@ -3542,14 +3605,6 @@ 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 wrapper
Box::pin(ucs_logging_wrapper(
router_data,
@@ -3559,67 +3614,11 @@ pub async fn call_unified_connector_service_for_refund_sync(
execution_mode,
|mut router_data, grpc_request, grpc_headers| async move {
// Call UCS refund_sync method
- let response = match ucs_client
+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper`.
+ let response = ucs_client
.refund_get(grpc_request, connector_auth_metadata, grpc_headers)
.await
- {
- 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()
- {
- let (code, message, status_code, reason, connector,
- network_decline_code, network_advice_code, network_error_message) = (
- &inner.code, &inner.message, inner.status_code, &inner.reason,
- &inner.connector, &inner.network_decline_code,
- &inner.network_advice_code, &inner.network_error_message,
- );
- logger::info!(
- "Connector error via UCS for refund sync (connector {}, status {}): {} - {}",
- connector,
- status_code,
- code,
- message
- );
- router_data.response = Err(ErrorResponse {
- code: code.clone(),
- message: message.clone(),
- reason: reason.clone(),
- status_code,
- attempt_status: None,
- connector_transaction_id: inner.connector_transaction_id.clone(),
- connector_response_reference_id: None,
- network_decline_code: network_decline_code.clone(),
- network_advice_code: network_advice_code.clone(),
- network_error_message: network_error_message.clone(),
- connector_metadata: None,
- });
- router_data.connector_http_status_code = Some(status_code);
- return Ok((router_data, (), payments_grpc::RefundResponse::default()));
- }
- let api_error = report.current_context().switch();
- return Err(report
- .change_context(api_error)
- .attach_printable("UCS refund sync execution failed"));
- }
- };
+ .attach_printable("UCS refund sync execution failed")?;
let grpc_response = response.into_inner();
@@ -3629,7 +3628,6 @@ pub async fn call_unified_connector_service_for_refund_sync(
grpc_response.clone(),
prev_refund_status,
)
- .change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to transform UCS refund get response")?;
router_data.response = refund_response_data;
diff --git a/crates/router/src/core/unified_connector_service/kill_switch.rs b/crates/router/src/core/unified_connector_service/kill_switch.rs
index ea9bf53845..4fa77429be 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,9 @@
-//! Returns a rollout scope to the direct connector integration when a Unified Connector Service
-//! call fails.
+//! Returns a rollout scope to the shadow connector integration when a Unified Connector Service
+//! call fails more than a configurable threshold number of times.
//!
-//! 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.
+//! 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.
use std::str::FromStr;
@@ -18,7 +18,6 @@ use crate::{
consts,
core::{
errors, metrics,
- payments::helpers::is_config_flag_enabled,
unified_connector_service::{
build_merchant_rollout_scope, determine_connector_integration_type,
},
@@ -26,8 +25,16 @@ use crate::{
routes::SessionState,
};
-/// Redis key holding the trip for a scope.
-fn trip_key(rollout_scope: &str) -> String {
+/// Hash field name for the failure counter.
+const COUNTER_FIELD: &str = "counter";
+
+/// Whether the counter has reached or exceeded the threshold.
+fn exceeds_threshold(count: u64, threshold: u64) -> bool {
+ count >= threshold
+}
+
+/// Redis key holding the failure counter for a scope.
+fn counter_key(rollout_scope: &str) -> String {
format!("{}_{rollout_scope}", consts::UCS_KILL_SWITCH_REDIS_PREFIX)
}
@@ -44,49 +51,67 @@ fn rollout_scope_in(key_or_scope: &str) -> &str {
}
}
-/// Whether the kill switch has tripped for this scope.
+/// Whether the kill switch should divert this scope to shadow mode.
///
-/// 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.
+/// Checks: per-scope `kill_switch_enabled` from RolloutConfig must be true. Then reads the
+/// failure counter from Redis and compares against the threshold.
+///
+/// Fails closed: a Redis error routes to shadow (the safe path).
+pub async fn is_kill_switched(
+ state: &SessionState,
+ rollout_scope: &str,
+ kill_switch_enabled: bool,
+ kill_switch_threshold: u64,
+) -> bool {
+ if kill_switch_enabled {
+ match read_counter(state, rollout_scope).await {
+ Ok(count) => {
+ let exceeded = exceeds_threshold(count, kill_switch_threshold);
+ if exceeded {
+ logger::debug!(
+ rollout_scope = %rollout_scope,
+ count = count,
+ threshold = kill_switch_threshold,
+ "ucs_kill_switch: counter exceeds threshold, routing to shadow"
+ );
+ }
+ exceeded
+ }
+ // Fails closed: the scope goes to shadow when Redis cannot answer.
Err(error) => {
logger::error!(
?error,
rollout_scope = %rollout_scope,
- "ucs_kill_switch: trip unreadable, routing to the direct integration"
+ "ucs_kill_switch: counter unreadable, routing to shadow"
);
true
}
}
} else {
+ logger::debug!(
+ rollout_scope = %rollout_scope,
+ kill_switch_enabled = kill_switch_enabled,
+ "ucs_kill_switch: kill switch is disabled for this scope"
+ );
false
}
}
-/// Reads the trip. Redis failures short-circuit to the caller, which decides the safe answer.
-async fn read_trip(
+/// Reads the failure counter from the hash. Returns 0 if the key or field does not exist.
+/// Redis connection or read errors are propagated so the caller can fail closed.
+async fn read_counter(
state: &SessionState,
rollout_scope: &str,
-) -> error_stack::Result<bool, storage_impl::errors::RedisError> {
- let tripped = state
+) -> 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()?
- .exists::<()>(&trip_key(rollout_scope).as_str().into())
- .await?;
+ .get_hash_field::<Option<u64>>(&key, COUNTER_FIELD)
+ .await?
+ .unwrap_or(0);
- 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)
+ Ok(count)
}
/// What a failing UCS call was for. A struct because transposing two of six positional strings
@@ -100,13 +125,13 @@ pub struct UcsFailureContext<'a> {
pub payment_method_type: Option<common_enums::PaymentMethodType>,
}
-/// A failure that qualifies to trip, and the scope it would trip.
+/// A failure that qualifies to increment the counter, and the scope it targets.
struct TrippableFailure {
rollout_scope: String,
reason: UcsKillSwitchReason,
}
-/// Records a qualifying UCS failure, and trips its scope when the switch is turned on.
+/// 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(
@@ -120,7 +145,7 @@ pub async fn record_failure(
}
}
-/// Counts the failure, trips its scope when the switch is turned on, and reports what happened.
+/// Increments the counter and logs the failure.
async fn record_trippable_failure(
state: &SessionState,
failure: &TrippableFailure,
@@ -136,16 +161,8 @@ async fn record_trippable_failure(
),
);
- let outcome = if is_config_flag_enabled(state, consts::UCS_KILL_SWITCH_ENABLED).await {
- trip(state, failure, context).await
- } else {
- TripOutcome::SwitchOff
- };
+ let outcome = increment_counter(state, failure, context).await;
- // 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,
@@ -157,7 +174,7 @@ async fn record_trippable_failure(
reason = %failure.reason,
outcome = %outcome,
ucs_error = ?error,
- "ucs_kill_switch"
+ "UCS_KILL_SWITCH_COUNTER_INCREMENTED"
);
}
@@ -202,110 +219,94 @@ async fn is_ucs_only_connector(state: &SessionState, connector_name: &str) -> bo
}
}
-/// 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.
+/// What came of a counter increment.
#[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.
+enum IncrementOutcome {
+ /// Counter was incremented successfully.
+ Incremented,
+ /// Redis refused the write.
WriteFailed,
}
-/// Writes the trip. `SET NX` makes it exactly-once: one concurrent writer wins, the rest no-op.
-async fn trip(
+/// Increments the failure counter and refreshes its TTL.
+async fn increment_counter(
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) => {
+) -> IncrementOutcome {
+ match write_counter(state, &failure.rollout_scope).await {
+ Ok(counts) => {
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())
+ ("reason", failure.reason.to_string())
),
);
- TripOutcome::Tripped
+ logger::info!(
+ rollout_scope = %failure.rollout_scope,
+ count = ?counts,
+ "ucs_kill_switch: counter incremented"
+ );
+
+ IncrementOutcome::Incremented
}
- 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"
+ rollout_scope = %failure.rollout_scope,
+ "ucs_kill_switch: could not increment counter"
);
- TripOutcome::WriteFailed
+ IncrementOutcome::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(
+/// Increments the failure counter (HINCRBY) and refreshes its TTL (EXPIRE).
+/// Two separate Redis calls — not atomic, but harmless: worst case the TTL refresh
+/// fails and the counter expires on its previous TTL.
+async fn write_counter(
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)?;
+) -> 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();
- 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),
- )
+ let result = conn
+ .increment_fields_in_hash(&key, &[(COUNTER_FIELD, 1)])
+ .await?;
+
+ conn.set_expiry(&key, consts::UCS_KILL_SWITCH_TTL_IN_SECONDS)
.await
-}
+ .inspect_err(|error| {
+ logger::warn!(
+ ?error,
+ rollout_scope = %rollout_scope,
+ "ucs_kill_switch: failed to refresh counter TTL"
+ );
+ })
+ .ok();
-/// 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,
+ Ok(result)
}
-/// 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.
+/// Whether this scope has a counter, its current value, and whether it exceeds the threshold.
#[derive(Debug, serde::Serialize)]
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.
+ pub threshold: Option<u64>,
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.
+/// 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);
@@ -314,56 +315,82 @@ pub async fn reset(state: SessionState, listed_key: String) -> errors::RouterRes
.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())
+ .delete_key(&counter_key(rollout_scope).as_str().into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to delete the UCS kill switch trip")?;
+ .attach_printable("Failed to delete the UCS kill switch counter")?;
match reply {
redis_interface::DelReply::KeyDeleted => {
logger::info!(
rollout_scope = %rollout_scope,
- "ucs_kill_switch: trip cleared via api"
+ "ucs_kill_switch: counter 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}"),
+ message: format!("No UCS kill switch counter 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.
+/// Reads the counter so an on-call engineer can inspect it without Redis or log access.
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())
+ let counter_value: u64 = read_counter(&state, rollout_scope)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to read the UCS kill switch trip")?;
+ .attach_printable("Failed to read the UCS kill switch counter")?;
+
+ // Fetch the kill_switch_threshold from the RolloutConfig for this scope.
+ // Uses the scope-level config key (without org prefix) since trip_status
+ // doesn't have org context.
+ let config_key = format!(
+ "{}_{}",
+ consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
+ rollout_scope
+ );
+ let threshold: Option<u64> = state
+ .store
+ .find_config_by_key_unwrap_or(
+ &config_key,
+ Some(consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED.to_string()),
+ )
+ .await
+ .ok()
+ .filter(|config| config.config != consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED)
+ .and_then(|config| {
+ serde_json::from_str::<crate::core::payments::helpers::RolloutConfig>(&config.config)
+ .inspect_err(|err| {
+ logger::warn!(
+ ?err,
+ config_key = %config_key,
+ "ucs_kill_switch: failed to parse RolloutConfig for threshold lookup"
+ );
+ })
+ .ok()
+ })
+ .map(|rc| rc.kill_switch_threshold);
+
+ let tripped = match threshold {
+ Some(t) => exceeds_threshold(counter_value, t),
+ None => counter_value > 0,
+ };
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()),
+ counter: counter_value,
+ threshold,
+ tripped,
},
))
}
@@ -438,8 +465,6 @@ mod tests {
#[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)
@@ -448,8 +473,6 @@ mod tests {
#[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),
@@ -467,12 +490,10 @@ mod tests {
#[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,
@@ -481,7 +502,6 @@ mod tests {
),
"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"
@@ -490,8 +510,6 @@ mod tests {
#[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!(
@@ -526,8 +544,8 @@ mod tests {
}
#[test]
- fn trip_key_cannot_collide_with_a_rollout_config_key() {
- let key = trip_key(&rollout_scope(PaymentMethod::Card, None, "Authorize"));
+ fn counter_key_cannot_collide_with_a_rollout_config_key() {
+ let key = counter_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));