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): shared keepalive gRPC channel, fatal build errors, real health check, transport failure class (#14273)

gopikrishna0004b263b28fd7b
diff --git a/config/config.example.toml b/config/config.example.toml
index 58cf99d5b9..26fe977a78 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1501,6 +1501,9 @@ admin_secret = "" # Shared secret sent as x-admin-secret o
base_url = "http://localhost:8000" # Unified Connector Service Base URL
connection_timeout = 10 # Connection Timeout Duration in Seconds
request_timeout = 35 # Per-RPC Request Timeout in Seconds
+keep_alive_interval = 30 # HTTP/2 PING keepalive interval in Seconds on the shared channel
+keep_alive_timeout = 20 # Time in Seconds to wait for a keepalive PING acknowledgement before the connection is treated as dead
+tcp_keepalive = 60 # TCP keepalive idle time in Seconds on the shared channel
ucs_only_connectors = "imerchantsolutions, paytm, phonepe, hyperpg, revolv3, fiservcommercehub, absa_sanlam, interpayments, dlocal, barclaycard, tsys_transit, jpmorgan, datatrans, givepayments, tesouro, citigate, ilixium, moneris, elavon, worldpayraft, globalpay, rapyd, paynearme, jpmorgan_orbital, saferpay, d24, etisalat, globalpayments_heartland, paydotcom, merchante, nsure" # Comma-separated list of connectors that use UCS only
ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list of connectors to disable UCS PSync call
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 8b950531aa..86465a139d 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -475,6 +475,9 @@ payment_method = "payment_method_types" # <payment_method> = comma-separated clo
base_url = "http://localhost:8000" # Unified Connector Service Base URL
connection_timeout = 10 # Connection Timeout Duration in Seconds
request_timeout = 35 # Per-RPC Request Timeout in Seconds
+keep_alive_interval = 30 # HTTP/2 PING keepalive interval in Seconds on the shared channel
+keep_alive_timeout = 20 # Time in Seconds to wait for a keepalive PING acknowledgement before the connection is treated as dead
+tcp_keepalive = 60 # TCP keepalive idle time in Seconds on the shared channel
ucs_only_connectors = "imerchantsolutions, paytm, phonepe, hyperpg, revolv3, fiservcommercehub, absa_sanlam, interpayments, payconex, dlocal, barclaycard, jpmorgan, datatrans, tsys_transit, givepayments, tesouro, citigate, ilixium, moneris, elavon, worldpayraft, globalpay, rapyd, paynearme, jpmorgan_orbital, saferpay, d24, etisalat, globalpayments_heartland, paydotcom, merchante, nsure" # Comma-separated list of connectors that use UCS only
ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list of connectors to disable UCS PSync call
diff --git a/config/development.toml b/config/development.toml
index 407638f665..384a5ef9b5 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -1627,6 +1627,9 @@ enabled = "true"
base_url = "http://localhost:8000"
connection_timeout = 10
request_timeout = 35
+keep_alive_interval = 30
+keep_alive_timeout = 20
+tcp_keepalive = 60
ucs_only_connectors = "imerchantsolutions, paytm, phonepe, hyperpg, revolv3, fiservcommercehub, absa_sanlam, interpayments, payconex, dlocal, barclaycard, tsys_transit, jpmorgan, datatrans, givepayments, tesouro, citigate, ilixium, moneris, elavon, worldpayraft, globalpay, rapyd, paynearme, jpmorgan_orbital, saferpay, d24, etisalat, globalpayments_heartland, paydotcom, merchante, nsure" # Comma-separated list of connectors that use UCS only
ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list of connectors to disable UCS PSync call
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs
index 715f89a5be..a5481eeadc 100644
--- a/crates/external_services/src/grpc_client.rs
+++ b/crates/external_services/src/grpc_client.rs
@@ -104,8 +104,10 @@ pub struct GrpcClientSettings {
impl GrpcClientSettings {
/// # Panics
///
- /// This function will panic if it fails to establish a connection with the gRPC server.
- /// This function will be called at service startup.
+ /// This function will panic if it fails to establish a connection with the gRPC server, or if
+ /// the Unified Connector Service is configured but its client cannot be built. Both are fatal
+ /// at service startup by design: a pod that silently loses UCS would route every payment down
+ /// the direct connector path, which is not an option for `ucs_only_connectors`.
#[allow(clippy::expect_used)]
pub async fn get_grpc_client_interface(&self) -> Arc<GrpcClients> {
#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]
@@ -136,7 +138,9 @@ impl GrpcClientSettings {
.expect("Failed to build gRPC connections");
let unified_connector_service_client =
- UnifiedConnectorServiceClient::build_connections(self).await;
+ UnifiedConnectorServiceClient::build_connections(self)
+ .await
+ .expect("Failed to build the Unified Connector Service client from configuration");
#[cfg(feature = "revenue_recovery")]
let recovery_decider_client = {
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index e11291c51a..797fc90444 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -6,7 +6,7 @@ use error_stack::ResultExt;
pub use hyperswitch_interfaces::unified_connector_service::transformers::UnifiedConnectorServiceError;
use hyperswitch_masking::{PeekInterface, Secret};
use router_env::logger;
-use tokio::time::{timeout, Duration};
+use tokio::time::Duration;
use tonic::{
metadata::{MetadataMap, MetadataValue},
transport::Uri,
@@ -62,6 +62,11 @@ pub struct UnifiedConnectorServiceClient {
pub surcharge_service_client: payments_grpc::surcharge_service_client::SurchargeServiceClient<UcsChannel>,
/// The Fraud and Risk Management Service Client
pub frm_service_client: payments_grpc::fraud_and_risk_management_service_client::FraudAndRiskManagementServiceClient<UcsChannel>,
+ /// Standard gRPC health client (grpc.health.v1) over the same shared channel, used by the
+ /// router health endpoint to prove UCS is reachable from this pod. Gated like the module it
+ /// comes from: the health proto is only compiled under `dynamic_routing`.
+ #[cfg(feature = "dynamic_routing")]
+ pub health_client: super::health_check_client::HealthClient<UcsChannel>,
}
/// Contains the Unified Connector Service Client config
@@ -77,6 +82,19 @@ pub struct UnifiedConnectorServiceClientConfig {
#[serde(default)]
pub request_timeout: UcsRequestTimeoutInSeconds,
+ /// HTTP/2 PING keepalive interval (seconds) on the shared channel. PINGs are sent while idle.
+ #[serde(default)]
+ pub keep_alive_interval: UcsKeepAliveIntervalInSeconds,
+
+ /// Time (seconds) to wait for a keepalive PING acknowledgement before the connection is
+ /// treated as dead and re-established.
+ #[serde(default)]
+ pub keep_alive_timeout: UcsKeepAliveTimeoutInSeconds,
+
+ /// TCP keepalive idle time (seconds) on the shared channel.
+ #[serde(default)]
+ pub tcp_keepalive: UcsTcpKeepAliveInSeconds,
+
/// Set of external services/connectors available for the unified connector service
#[serde(default, deserialize_with = "deserialize_hashset")]
pub ucs_only_connectors: HashSet<Connector>,
@@ -114,6 +132,57 @@ impl UcsRequestTimeoutInSeconds {
}
}
+/// HTTP/2 PING keepalive interval for the Unified Connector Service channel, in seconds.
+#[derive(Debug, Clone, Copy, serde::Deserialize, serde::Serialize)]
+pub struct UcsKeepAliveIntervalInSeconds(u64);
+
+impl Default for UcsKeepAliveIntervalInSeconds {
+ fn default() -> Self {
+ Self(consts::DEFAULT_UCS_KEEP_ALIVE_INTERVAL_SECS)
+ }
+}
+
+impl UcsKeepAliveIntervalInSeconds {
+ /// Return the interval as a [`Duration`].
+ pub fn as_duration(self) -> Duration {
+ Duration::from_secs(self.0)
+ }
+}
+
+/// Keepalive PING acknowledgement timeout for the Unified Connector Service channel, in seconds.
+#[derive(Debug, Clone, Copy, serde::Deserialize, serde::Serialize)]
+pub struct UcsKeepAliveTimeoutInSeconds(u64);
+
+impl Default for UcsKeepAliveTimeoutInSeconds {
+ fn default() -> Self {
+ Self(consts::DEFAULT_UCS_KEEP_ALIVE_TIMEOUT_SECS)
+ }
+}
+
+impl UcsKeepAliveTimeoutInSeconds {
+ /// Return the timeout as a [`Duration`].
+ pub fn as_duration(self) -> Duration {
+ Duration::from_secs(self.0)
+ }
+}
+
+/// TCP keepalive idle time for the Unified Connector Service channel, in seconds.
+#[derive(Debug, Clone, Copy, serde::Deserialize, serde::Serialize)]
+pub struct UcsTcpKeepAliveInSeconds(u64);
+
+impl Default for UcsTcpKeepAliveInSeconds {
+ fn default() -> Self {
+ Self(consts::DEFAULT_UCS_TCP_KEEPALIVE_SECS)
+ }
+}
+
+impl UcsTcpKeepAliveInSeconds {
+ /// Return the idle time as a [`Duration`].
+ pub fn as_duration(self) -> Duration {
+ Duration::from_secs(self.0)
+ }
+}
+
/// Contains the Connector Auth Type and related authentication data.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ConnectorAuthMetadata {
@@ -195,78 +264,49 @@ pub struct HyperswitchVaultMetadata {
pub vault_auth_data: VaultConnectorAuth,
}
-/// Connects `endpoint` eagerly, bounded by `connection_timeout`, naming `client_name` on failure.
+/// Failure to build the Unified Connector Service client from configuration.
///
-/// `None` means the caller must abandon the whole client: an unreachable service is reported here
-/// and nulls [`UnifiedConnectorServiceClient`], so the router serves from the direct connector
-/// path rather than routing live traffic at a service it cannot reach.
-pub async fn connect_ucs_endpoint(
- endpoint: &tonic::transport::Endpoint,
- connection_timeout: UcsConnectionTimeoutInSeconds,
- client_name: &str,
-) -> Option<tonic::transport::Channel> {
- match timeout(connection_timeout.as_duration(), endpoint.connect()).await {
- Ok(Ok(channel)) => Some(channel),
- Ok(Err(err)) => {
- logger::error!(
- "Failed to connect to Unified Connector Service for {}: {:?}",
- client_name,
- err
- );
- None
- }
- Err(err) => {
- logger::error!(
- "Connection to Unified Connector Service timed out for {}: {:?}",
- client_name,
- err
- );
- None
- }
- }
+/// Fatal at startup by design: a configured UCS that cannot be set up must stop the pod from
+/// starting rather than silently degrading every payment on this pod to the direct connector
+/// path, which is not an option for `ucs_only_connectors`.
+#[derive(Debug, thiserror::Error)]
+pub enum UcsClientBuildError {
+ /// The configured `base_url` is not a valid URI
+ #[error("Failed to parse Unified Connector Service base_url as a URI: {0}")]
+ InvalidUri(String),
+ /// The transport boundary did not yield a usable channel
+ #[error("Unified Connector Service transport could not be constructed")]
+ TransportUnavailable,
}
-/// Builds a gRPC client. `$connection_timeout` bounds connect; `$request_timeout` bounds each RPC.
-///
-/// The connect is eager and gating: an unreachable service is logged and nulls the whole client,
-/// so the router serves from the direct connector path instead of routing live traffic at a
-/// service it cannot reach. That is the behaviour in every mode this router actually runs in,
-/// recording included, so a recording never diverges from the deployment it records.
+/// Builds the single shared channel to the Unified Connector Service.
///
-/// Under the `deja` feature the connect is handed to `connect_or_substitute`, which runs it
-/// unchanged except under replay — where no rpc is ever issued live, so the transport is dead
-/// weight and the boundary stands in for it. This file expresses no opinion about deja's modes;
-/// that decision lives in the boundary adapter.
-#[macro_export]
-macro_rules! build_grpc_client {
- ($client:ty, $name:expr, $uri:expr, $connection_timeout:expr, $request_timeout:expr) => {{
- let endpoint = tonic::transport::Channel::builder($uri.clone())
- .timeout($request_timeout.as_duration());
-
- // deja: the same eager connect, handed to the gRPC egress boundary so every unary rpc is
- // recorded/substituted at the wire level (rank-2 identity). The boundary runs the connect
- // unchanged in every mode but replay, where it stands in for a transport nothing will
- // use. Feature-off performs the connect directly and passes the raw channel through.
- #[cfg(feature = "deja")]
- let channel = $crate::grpc_client::deja_transport::connect_or_substitute(|| {
- $crate::grpc_client::unified_connector_service::connect_ucs_endpoint(
- &endpoint,
- $connection_timeout,
- $name,
- )
- })
- .await?;
-
- #[cfg(not(feature = "deja"))]
- let channel = $crate::grpc_client::unified_connector_service::connect_ucs_endpoint(
- &endpoint,
- $connection_timeout,
- $name,
- )
- .await?;
-
- <$client>::new(channel)
- }};
+/// One lazily connected HTTP/2 connection carries every UCS service client, so no client-specific
+/// channel can sit idle for hours. HTTP/2 PING keepalive runs while idle: a connection that dies
+/// without a GOAWAY is detected within `keep_alive_interval + keep_alive_timeout` and rebuilt by
+/// tonic's reconnect layer before the next RPC, instead of the next RPC failing with
+/// `transport error`. `connect_lazy` performs no I/O here; the first RPC (or the router health
+/// check) opens the connection, and a failed dial fails only that RPC and is retried on the next.
+fn build_ucs_channel(
+ uri: Uri,
+ config: &UnifiedConnectorServiceClientConfig,
+) -> tonic::transport::Channel {
+ tonic::transport::Channel::builder(uri)
+ .connect_timeout(config.connection_timeout.as_duration())
+ .timeout(config.request_timeout.as_duration())
+ .http2_keep_alive_interval(config.keep_alive_interval.as_duration())
+ .keep_alive_timeout(config.keep_alive_timeout.as_duration())
+ .keep_alive_while_idle(true)
+ .tcp_keepalive(Some(config.tcp_keepalive.as_duration()))
+ // Flow-control windows are deliberately left at hyper's defaults (5 MiB connection,
+ // 2 MiB stream). They are not the per-connection 64 KiB of the HTTP/2 spec, so a single
+ // shared connection is not a throughput regression against the eleven it replaces:
+ // gRPC payloads here are a few KiB and never approach the window, and the windows are
+ // receive-side credit rather than a bandwidth cap. `http2_adaptive_window` is
+ // intentionally not enabled; it would *lower* the initial windows to 65,535 bytes and
+ // rely on BDP sampling to grow them back, which only helps on high bandwidth-delay
+ // links carrying large payloads, not on same-region RPCs of this size.
+ .connect_lazy()
}
/// VGS proxy data
@@ -279,176 +319,102 @@ pub struct VgsMetadata {
}
impl UnifiedConnectorServiceClient {
- /// Builds the connection to the gRPC service
- pub async fn build_connections(config: &GrpcClientSettings) -> Option<Self> {
- match &config.unified_connector_service {
- Some(unified_connector_service_client_config) => {
- let uri: Uri = match unified_connector_service_client_config
- .base_url
- .get_string_repr()
- .parse()
- {
- Ok(parsed_uri) => parsed_uri,
- Err(err) => {
- logger::error!(error = ?err, "Failed to parse URI for Unified Connector Service");
- return None;
- }
- };
-
- let connection_timeout = unified_connector_service_client_config.connection_timeout;
- let request_timeout = unified_connector_service_client_config.request_timeout;
-
- let payment_service_client = build_grpc_client!(
- payments_grpc::payment_service_client::PaymentServiceClient<
- UcsChannel,
- >,
- "payment_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let refund_service_client = build_grpc_client!(
- payments_grpc::refund_service_client::RefundServiceClient<
- UcsChannel,
- >,
- "refund_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let event_service_client = build_grpc_client!(
- payments_grpc::event_service_client::EventServiceClient<
- UcsChannel,
- >,
- "event_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let recurring_payment_service_client = build_grpc_client!(
- payments_grpc::recurring_payment_service_client::RecurringPaymentServiceClient<
- UcsChannel,
- >,
- "recurring_payment_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let dispute_service_client = build_grpc_client!(
- payments_grpc::dispute_service_client::DisputeServiceClient<
- UcsChannel,
- >,
- "dispute_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let payment_method_service_client = build_grpc_client!(
- payments_grpc::payment_method_service_client::PaymentMethodServiceClient<
- UcsChannel,
- >,
- "payment_method_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let customer_service_client = build_grpc_client!(
- payments_grpc::customer_service_client::CustomerServiceClient<
- UcsChannel,
- >,
- "customer_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let merchant_authentication_service_client = build_grpc_client!(
- payments_grpc::merchant_authentication_service_client::MerchantAuthenticationServiceClient<UcsChannel>,
- "merchant_authentication_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let payment_method_authentication_service_client = build_grpc_client!(
- payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient<UcsChannel>,
- "payment_method_authentication_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let payout_service_client = build_grpc_client!(
- payments_grpc::payout_service_client::PayoutServiceClient<
- UcsChannel,
- >,
- "payout_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let surcharge_service_client = build_grpc_client!(
- payments_grpc::surcharge_service_client::SurchargeServiceClient<
- UcsChannel,
- >,
- "surcharge_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- let frm_service_client = build_grpc_client!(
- payments_grpc::fraud_and_risk_management_service_client::FraudAndRiskManagementServiceClient<
- UcsChannel,
- >,
- "frm_service_client",
- uri,
- connection_timeout,
- request_timeout
- );
-
- // Replay connected nothing — the boundary stands in for every channel — so the
- // usual claim would be false there. Every other mode performed the same eager
- // connect it always did.
- #[cfg(feature = "deja")]
- if deja::__private::runtime_mode().is_replay() {
- logger::info!(
- "Unified Connector Service clients substituted at the deja boundary; no transport connected"
- );
- } else {
- logger::info!("Successfully connected to Unified Connector Service");
- }
-
- #[cfg(not(feature = "deja"))]
- logger::info!("Successfully connected to Unified Connector Service");
-
- Some(Self {
- payment_service_client,
- refund_service_client,
- event_service_client,
- recurring_payment_service_client,
- dispute_service_client,
- payment_method_service_client,
- customer_service_client,
- merchant_authentication_service_client,
- payment_method_authentication_service_client,
- payout_service_client,
- surcharge_service_client,
- frm_service_client,
- })
- }
- None => {
- router_env::logger::error!(?config.unified_connector_service, "Unified Connector Service config is missing");
- None
- }
- }
+ /// Builds every UCS service client over one shared channel.
+ ///
+ /// Returns `Ok(None)` when UCS is not configured. Returns `Err` when it is configured but the
+ /// client cannot be built; the caller treats that as fatal at startup.
+ pub async fn build_connections(
+ config: &GrpcClientSettings,
+ ) -> Result<Option<Self>, UcsClientBuildError> {
+ let Some(ucs_config) = &config.unified_connector_service else {
+ logger::info!("Unified Connector Service is not configured; client not built");
+ return Ok(None);
+ };
+
+ let uri: Uri = ucs_config.base_url.get_string_repr().parse().map_err(
+ |err: tonic::codegen::http::uri::InvalidUri| {
+ logger::error!(error = ?err, "Failed to parse URI for Unified Connector Service");
+ UcsClientBuildError::InvalidUri(err.to_string())
+ },
+ )?;
+
+ let channel = build_ucs_channel(uri, ucs_config);
+
+ // deja: the same channel handed to the gRPC egress boundary so every unary rpc is
+ // recorded/substituted at the wire level. Under replay no transport is connected at all.
+ #[cfg(feature = "deja")]
+ let transport: UcsChannel =
+ super::deja_transport::connect_or_substitute(|| async { Some(channel) })
+ .await
+ .ok_or(UcsClientBuildError::TransportUnavailable)?;
+
+ #[cfg(not(feature = "deja"))]
+ let transport: UcsChannel = channel;
+
+ logger::info!(
+ keep_alive_interval = ?ucs_config.keep_alive_interval.as_duration(),
+ keep_alive_timeout = ?ucs_config.keep_alive_timeout.as_duration(),
+ tcp_keepalive = ?ucs_config.tcp_keepalive.as_duration(),
+ "Unified Connector Service clients built over one shared lazily-connected channel"
+ );
+
+ Ok(Some(Self {
+ payment_service_client: payments_grpc::payment_service_client::PaymentServiceClient::new(
+ transport.clone(),
+ ),
+ refund_service_client: payments_grpc::refund_service_client::RefundServiceClient::new(
+ transport.clone(),
+ ),
+ event_service_client: payments_grpc::event_service_client::EventServiceClient::new(
+ transport.clone(),
+ ),
+ recurring_payment_service_client:
+ payments_grpc::recurring_payment_service_client::RecurringPaymentServiceClient::new(
+ transport.clone(),
+ ),
+ dispute_service_client: payments_grpc::dispute_service_client::DisputeServiceClient::new(
+ transport.clone(),
+ ),
+ payment_method_service_client:
+ payments_grpc::payment_method_service_client::PaymentMethodServiceClient::new(
+ transport.clone(),
+ ),
+ customer_service_client: payments_grpc::customer_service_client::CustomerServiceClient::new(
+ transport.clone(),
+ ),
+ merchant_authentication_service_client:
+ payments_grpc::merchant_authentication_service_client::MerchantAuthenticationServiceClient::new(
+ transport.clone(),
+ ),
+ payment_method_authentication_service_client:
+ payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient::new(
+ transport.clone(),
+ ),
+ payout_service_client: payments_grpc::payout_service_client::PayoutServiceClient::new(
+ transport.clone(),
+ ),
+ surcharge_service_client:
+ payments_grpc::surcharge_service_client::SurchargeServiceClient::new(
+ transport.clone(),
+ ),
+ frm_service_client:
+ payments_grpc::fraud_and_risk_management_service_client::FraudAndRiskManagementServiceClient::new(
+ transport.clone(),
+ ),
+ #[cfg(feature = "dynamic_routing")]
+ health_client: super::health_check_client::HealthClient::new(transport.clone()),
+ }))
+ }
+
+ /// Standard gRPC health check (grpc.health.v1 `Check`, empty service name) against UCS over
+ /// the shared channel. `Ok(true)` means UCS reported `SERVING`.
+ #[cfg(feature = "dynamic_routing")]
+ pub async fn health_check(&self) -> Result<bool, tonic::Status> {
+ let request = tonic::Request::new(super::health_check_client::HealthCheckRequest {
+ service: String::new(),
+ });
+ let response = self.health_client.clone().check(request).await?;
+ Ok(response.into_inner().status() == super::health_check_client::ServingStatus::Serving)
}
/// Performs Payment Method Tokenize
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs
index 49f2744227..a23b0015cd 100644
--- a/crates/external_services/src/lib.rs
+++ b/crates/external_services/src/lib.rs
@@ -67,6 +67,20 @@ pub mod consts {
/// Default per-RPC timeout (seconds) for unified connector service calls.
pub(crate) const DEFAULT_UCS_REQUEST_TIMEOUT_SECS: u64 = 35;
+ /// Default HTTP/2 PING keepalive interval (seconds) on the shared channel to the unified
+ /// connector service. PINGs are sent while idle so a dead connection is detected and
+ /// re-established in the background instead of by the next payment RPC.
+ pub(crate) const DEFAULT_UCS_KEEP_ALIVE_INTERVAL_SECS: u64 = 30;
+
+ /// Default time (seconds) to wait for a keepalive PING acknowledgement before the
+ /// connection to the unified connector service is treated as dead. Matches the gRPC-Go
+ /// client default; a tighter value drops connections during ordinary load spikes.
+ pub(crate) const DEFAULT_UCS_KEEP_ALIVE_TIMEOUT_SECS: u64 = 20;
+
+ /// Default TCP keepalive idle time (seconds) on the shared channel to the unified connector
+ /// service. OS-level backstop for the HTTP/2 PING keepalive.
+ pub(crate) const DEFAULT_UCS_TCP_KEEPALIVE_SECS: u64 = 60;
+
/// General purpose base64 engine
#[cfg(any(feature = "aws_kms", feature = "gcp_kms"))]
pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose =
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index d390d40dd4..7bb35ec1a1 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -189,6 +189,9 @@ pub enum UnifiedConnectorServiceError {
code: tonic::Code,
/// Error message from UCS
message: String,
+ /// Present only when the status was produced by the router's own transport layer.
+ /// `None` for statuses returned by UCS as a gRPC response.
+ transport: Option<Box<UcsTransportFailure>>,
},
/// Connector error received through UCS.
@@ -1935,7 +1938,68 @@ impl ForeignFrom<payments_grpc::UpiSource>
}
}
+/// Detail of a gRPC status that the router's own transport produced, rather than one UCS
+/// returned as a response.
+///
+/// Holds the [`std::error::Error::source`] chain verbatim. Nothing is interpreted or classified:
+/// the chain already names the layer that failed and why, whether that is an `io::ErrorKind`, an
+/// HTTP/2 reason and initiator, a DNS failure or something a future hyper or tonic version
+/// introduces. Recording it whole is what makes the next transport failure diagnosable without
+/// having shipped code that anticipated it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UcsTransportFailure {
+ /// The `source()` chain, outermost first, root cause last, joined with " -> ". Router logs
+ /// only: an inner layer may render the UCS authority or a peer address.
+ pub source_chain: String,
+ /// The root cause alone, the last element of the chain. This is the part that names what
+ /// actually failed (`connection reset by peer (os error 104)`, `stream error received:
+ /// PROTOCOL_ERROR`, ...) and, unlike the outer layers, never carries an address or authority,
+ /// so it is what goes on the merchant-visible connector event.
+ pub root_cause: String,
+}
+
+impl UcsTransportFailure {
+ /// Builds from a [`tonic::Status`].
+ ///
+ /// Returns `None` when the status carries no error source, which is every status UCS returns
+ /// as a normal gRPC response. A `Some` means the status was produced locally by the transport.
+ /// That covers both a connection that was unusable before the request was written and a stream
+ /// that failed after UCS had already processed the request, so it does not by itself say the
+ /// request was unsent; the chain does.
+ pub fn from_status(status: &tonic::Status) -> Option<Self> {
+ let mut source: &(dyn std::error::Error + 'static) = std::error::Error::source(status)?;
+ let mut parts: Vec<String> = Vec::new();
+
+ loop {
+ parts.push(source.to_string());
+ match source.source() {
+ Some(next) => source = next,
+ None => break,
+ }
+ }
+
+ let root_cause = parts.last().cloned().unwrap_or_default();
+
+ Some(Self {
+ source_chain: parts.join(" -> "),
+ root_cause,
+ })
+ }
+}
+
impl UnifiedConnectorServiceError {
+ /// Client-side transport failure detail, present only when the status was produced by the
+ /// router's own transport rather than returned by UCS.
+ pub fn transport_failure(&self) -> Option<&UcsTransportFailure> {
+ match self {
+ Self::TonicStatus {
+ transport: Some(transport),
+ ..
+ } => Some(transport.as_ref()),
+ _ => None,
+ }
+ }
+
/// Converts tonic::Code to HTTP status code.
pub fn tonic_to_http_status(code: tonic::Code) -> u16 {
match code {
@@ -1999,6 +2063,7 @@ impl UnifiedConnectorServiceError {
.unwrap_or_else(|| Self::TonicStatus {
code: status.code(),
message: status.message().to_string(),
+ transport: UcsTransportFailure::from_status(status).map(Box::new),
})
}
@@ -2187,7 +2252,7 @@ impl UnifiedConnectorServiceError {
impl ErrorSwitch<ApiErrorResponse> for UnifiedConnectorServiceError {
fn switch(&self) -> ApiErrorResponse {
match self {
- Self::TonicStatus { code, message } => match code {
+ Self::TonicStatus { code, message, .. } => match code {
tonic::Code::InvalidArgument | tonic::Code::FailedPrecondition => {
ApiErrorResponse::InvalidRequestData {
message: message.clone(),
@@ -2230,7 +2295,7 @@ impl ErrorSwitch<ConnectorError> for UnifiedConnectorServiceError {
// recognize the error_code (or details were empty/undecodable).
// Server errors → ResponseHandlingFailed, Unimplemented → NotImplemented,
// anything else → RequestEncodingFailed as a safe client-error default.
- Self::TonicStatus { code, message } => match code {
+ Self::TonicStatus { code, message, .. } => match code {
_ if Self::tonic_status_is_ucs_server_error(*code) => {
ConnectorError::ResponseHandlingFailed
}
@@ -2469,6 +2534,7 @@ mod ucs_kill_switch_reason_tests {
UnifiedConnectorServiceError::TonicStatus {
code,
message: "from ucs".to_string(),
+ transport: None,
}
}
diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs
index 2d5cf7a329..af6244e96c 100644
--- a/crates/router/src/core/health_check.rs
+++ b/crates/router/src/core/health_check.rs
@@ -223,15 +223,64 @@ impl HealthCheckInterface for app::SessionState {
async fn health_check_unified_connector_service(
&self,
) -> CustomResult<HealthState, errors::HealthCheckUnifiedConnectorServiceError> {
- if let Some(_ucs_client) = &self.grpc_client.unified_connector_service_client {
- // For now, we'll just check if the client exists and is configured
- // In the future, this could be enhanced to make an actual health check call
- // to the unified connector service if it supports health check endpoints
- logger::debug!("Unified Connector Service client is configured and available");
- Ok(HealthState::Running)
- } else {
- logger::debug!("Unified Connector Service client not configured");
- Ok(HealthState::NotApplicable)
+ // TODO: remove this fallback once `health_check.proto` is compiled unconditionally.
+ //
+ // The `grpc.health.v1` stubs are generated inside the `dynamic_routing` block of
+ // `external_services/build.rs`. Without that feature there is no health client to call, so
+ // this reports only whether the client was configured, which is the behaviour that
+ // preceded the gRPC health check.
+ //
+ // The coupling is incidental: dynamic routing was the only consumer of the health proto
+ // when it was introduced. Compiling it unconditionally is deliberately left to a separate
+ // change, because it modifies build configuration shared with three other protos and the
+ // `deja_dynamic_routing_descriptor` that the deja boundary decodes at runtime.
+ //
+ // Release builds enable `dynamic_routing`, so deployed environments perform the real
+ // check. Local `cargo run` does not, which is the gap this TODO tracks.
+ #[cfg(not(feature = "dynamic_routing"))]
+ {
+ return Ok(match self.grpc_client.unified_connector_service_client {
+ Some(_) => {
+ logger::debug!("Unified Connector Service client is configured and available");
+ HealthState::Running
+ }
+ None => {
+ logger::debug!("Unified Connector Service client not configured");
+ HealthState::NotApplicable
+ }
+ });
+ }
+
+ #[cfg(feature = "dynamic_routing")]
+ match &self.grpc_client.unified_connector_service_client {
+ Some(ucs_client) => {
+ let serving = ucs_client
+ .health_check()
+ .await
+ .map_err(|status| {
+ logger::error!(
+ grpc_code = ?status.code(),
+ grpc_message = %status.message(),
+ "Unified Connector Service gRPC health check failed"
+ );
+ error_stack::report!(
+ errors::HealthCheckUnifiedConnectorServiceError::FailedToCallUnifiedConnectorService
+ )
+ })?;
+ if serving {
+ logger::debug!("Unified Connector Service reported SERVING");
+ Ok(HealthState::Running)
+ } else {
+ logger::error!("Unified Connector Service reported NOT_SERVING");
+ Err(error_stack::report!(
+ errors::HealthCheckUnifiedConnectorServiceError::FailedToCallUnifiedConnectorService
+ ))
+ }
+ }
+ None => {
+ logger::debug!("Unified Connector Service client not configured");
+ Ok(HealthState::NotApplicable)
+ }
}
}
}
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 2f4a8f444d..05cb2735ad 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -3926,10 +3926,27 @@ where
),
}
- let error_body = serde_json::json!({
+ let mut error_body = serde_json::json!({
"error": error.to_string(),
"error_type": "ucs_call_failed"
});
+ // The status was produced by the router's own transport rather than returned by
+ // UCS. The root cause goes on the connector event, which is merchant visible, and
+ // the full source chain goes to the log below. The chain carries the HTTP/2 reason
+ // and initiator, which distinguishes a request that was never written from a
+ // stream that failed after UCS had already processed it.
+ if let Some(transport) = error.current_context().transport_failure() {
+ if let Some(body) = error_body.as_object_mut() {
+ body.insert(
+ "transport_error".to_string(),
+ serde_json::Value::from(transport.root_cause.clone()),
+ );
+ }
+ logger::error!(
+ transport_error_chain = %transport.source_chain,
+ "ucs_call_failed: gRPC transport failure toward UCS"
+ );
+ }
let api_error: errors::ApiErrorResponse = error.current_context().switch();
(
api_error.status_code().as_u16(),
@@ -4131,10 +4148,27 @@ where
),
}
- let error_body = serde_json::json!({
+ let mut error_body = serde_json::json!({
"error": error.to_string(),
"error_type": "ucs_call_failed"
});
+ // The status was produced by the router's own transport rather than returned by
+ // UCS. The root cause goes on the connector event, which is merchant visible, and
+ // the full source chain goes to the log below. The chain carries the HTTP/2 reason
+ // and initiator, which distinguishes a request that was never written from a
+ // stream that failed after UCS had already processed it.
+ if let Some(transport) = error.current_context().transport_failure() {
+ if let Some(body) = error_body.as_object_mut() {
+ body.insert(
+ "transport_error".to_string(),
+ serde_json::Value::from(transport.root_cause.clone()),
+ );
+ }
+ logger::error!(
+ transport_error_chain = %transport.source_chain,
+ "ucs_call_failed: gRPC transport failure toward UCS"
+ );
+ }
(
error.current_context().http_status(),
Some(error_body),