Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(ucs): implement UCS granular flow for PSync (#10192)
Hrithikesh2583ea11adb0
diff --git a/Cargo.lock b/Cargo.lockindex 87b646ef92..a81ff4fe0d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4411,6 +4411,7 @@ dependencies = ["strum 0.26.3","thiserror 1.0.69","time",+ "tokio 1.48.0",][[package]]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex cb3553257e..c24e9a3196 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -2492,6 +2492,7 @@ pub enum ExecutionMode {#[default]Primary,Shadow,+ NotApplicable,}#[derive(diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex e2d927237e..af43d590a9 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -31,6 +31,7 @@ thiserror = "1.0.69"time = "0.3.41"unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "77eaaa6344de9657c83a65ed0d619f48dff0c4a5", package = "rust-grpc-client" }unified-connector-service-masking = { git = "https://github.com/juspay/hyperswitch", tag = "2025.09.24.0", package = "masking" }+tokio = { version = "1.45.1", features = ["macros", "rt-multi-thread"] }# First party crateshyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }masking = { version = "0.1.0", path = "../masking" }diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rsindex dbc21b99a9..950ae964c2 100644--- a/crates/hyperswitch_interfaces/src/api.rs+++ b/crates/hyperswitch_interfaces/src/api.rs@@ -12,6 +12,7 @@ pub mod files_v2;pub mod fraud_check;#[cfg(feature = "frm")]pub mod fraud_check_v2;+pub mod gateway;pub mod payments;pub mod payments_v2;#[cfg(feature = "payouts")]diff --git a/crates/hyperswitch_interfaces/src/api/gateway.rs b/crates/hyperswitch_interfaces/src/api/gateway.rsnew file mode 100644index 0000000000..51d392d814--- /dev/null+++ b/crates/hyperswitch_interfaces/src/api/gateway.rs@@ -0,0 +1,254 @@+//! Gateway abstraction layer for unified connector execution+//!+//! This module provides a unified interface for executing payment operations through either:+//! - Direct connector integration (traditional HTTP-based)+//! - Unified Connector Service (UCS) via gRPC+//!+//! The gateway abstraction allows seamless switching between execution paths without+//! requiring changes to individual flow implementations.++use async_trait::async_trait;+use common_enums::{CallConnectorAction, ExecutionMode, ExecutionPath};+use common_utils::{errors::CustomResult, request::Request};+use error_stack::ResultExt;+use hyperswitch_domain_models::router_data::RouterData;+use router_env::logger;++use crate::{+ api_client::{self, ApiClientWrapper},+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},+ errors::ConnectorError,+ helpers,+};++/// Minimal trait that gateway context must implement+///+/// This allows the framework to extract execution metadata without knowing+/// the concrete context structure. Implementation crates define their own+/// context types with whatever fields they need.+pub trait GatewayContext: Clone + Send + Sync {+ /// Get the execution path (Direct, UCS, or Shadow)+ fn execution_path(&self) -> ExecutionPath;++ /// Get the execution mode (Primary, Shadow, etc.)+ fn execution_mode(&self) -> ExecutionMode;+}++/// Payment gateway trait+///+/// Defines the interface for executing payment operations through different gateway types.+/// Implementations include DirectGateway and flow-specific UCS gateways.+///+/// # Type Parameters+/// * `State` - Application state (e.g., SessionState)+/// * `ConnectorData` - Connector-specific data type+/// * `F` - Flow type (e.g., domain::Authorize, domain::PSync)+/// * `Req` - Request data type+/// * `Resp` - Response data type+/// * `Context` - Gateway context type (must implement GatewayContext trait)+#[async_trait]+#[allow(clippy::too_many_arguments)]+pub trait PaymentGateway<State, ConnectorData, F, Req, Resp, Context>: Send + Sync+where+ State: Clone + Send + Sync + 'static + ApiClientWrapper,+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,+ F: Clone + std::fmt::Debug + Send + Sync + 'static,+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,+ Context: GatewayContext,+{+ /// Execute payment gateway operation+ async fn execute(+ self: Box<Self>,+ state: &State,+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,+ router_data: &RouterData<F, Req, Resp>,+ call_connector_action: CallConnectorAction,+ connector_request: Option<Request>,+ return_raw_connector_response: Option<bool>,+ context: Context,+ ) -> CustomResult<RouterData<F, Req, Resp>, ConnectorError>;+}++/// Direct gateway implementation+///+/// Executes payment operations through traditional HTTP connector integration.+/// This is the default execution path and maintains backward compatibility.+#[derive(Debug, Clone, Copy)]+pub struct DirectGateway;++#[async_trait]+impl<State, ConnectorData, F, Req, Resp, Context>+ PaymentGateway<State, ConnectorData, F, Req, Resp, Context> for DirectGateway+where+ State: Clone + Send + Sync + 'static + ApiClientWrapper,+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,+ F: Clone + std::fmt::Debug + Send + Sync + 'static,+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,+ Context: GatewayContext + 'static,+{+ async fn execute(+ self: Box<Self>,+ state: &State,+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,+ router_data: &RouterData<F, Req, Resp>,+ call_connector_action: CallConnectorAction,+ connector_request: Option<Request>,+ return_raw_connector_response: Option<bool>,+ _context: Context,+ ) -> CustomResult<RouterData<F, Req, Resp>, ConnectorError> {+ // Direct gateway delegates to the existing execute_connector_processing_step+ // This maintains backward compatibility with the traditional HTTP-based flow+ api_client::execute_connector_processing_step(+ state,+ connector_integration,+ router_data,+ call_connector_action,+ connector_request,+ return_raw_connector_response,+ )+ .await+ }+}++/// Flow gateway trait for determining execution path+///+/// This trait allows flows to specify which gateway implementation should be used+/// based on the execution path. Each flow implements this trait to provide+/// flow-specific gateway selection logic.+pub trait FlowGateway<State, ConnectorData, Req, Resp, Context>:+ Clone + std::fmt::Debug + Send + Sync + 'static+where+ State: Clone + Send + Sync + 'static + ApiClientWrapper,+ ConnectorData: Clone + RouterDataConversion<Self, Req, Resp> + Send + Sync + 'static,+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,+ Context: GatewayContext,+{+ /// Get the appropriate gateway for this flow based on execution path+ ///+ /// Returns a boxed gateway implementation that can be either:+ /// - DirectGateway for traditional HTTP connector integration+ /// - Flow-specific UCS gateway for gRPC integration+ fn get_gateway(+ execution_path: ExecutionPath,+ ) -> Box<dyn PaymentGateway<State, ConnectorData, Self, Req, Resp, Context>>;+}++/// Execute payment gateway operation (backward compatible version)+///+/// This version maintains backward compatibility by using direct execution when no context is provided.+/// Use `execute_payment_gateway_with_context` for UCS support.+pub async fn execute_payment_gateway<State, ConnectorData, F, Req, Resp, Context>(+ state: &State,+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,+ router_data: &RouterData<F, Req, Resp>,+ call_connector_action: CallConnectorAction,+ connector_request: Option<Request>,+ return_raw_connector_response: Option<bool>,+ context: Context,+) -> CustomResult<RouterData<F, Req, Resp>, ConnectorError>+where+ State: Clone + Send + Sync + 'static + ApiClientWrapper + helpers::GetComparisonServiceConfig,+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,+ F: Clone+ + std::fmt::Debug+ + Send+ + Sync+ + 'static+ + FlowGateway<State, ConnectorData, Req, Resp, Context>,+ Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,+ Context: GatewayContext + 'static,+{+ let execution_path = context.execution_path();++ match execution_path {+ ExecutionPath::Direct => {+ // Use direct execution for backward compatibility+ api_client::execute_connector_processing_step(+ state,+ connector_integration,+ router_data,+ call_connector_action,+ connector_request,+ return_raw_connector_response,+ )+ .await+ }+ ExecutionPath::UnifiedConnectorService => {+ let gateway: Box<dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context>> =+ F::get_gateway(execution_path);++ // Execute through selected gateway+ gateway+ .execute(+ state,+ connector_integration,+ router_data,+ call_connector_action,+ connector_request,+ return_raw_connector_response,+ context,+ )+ .await+ .attach_printable("Gateway execution failed")+ }+ ExecutionPath::ShadowUnifiedConnectorService => {+ let direct_router_data = api_client::execute_connector_processing_step(+ state,+ connector_integration.clone_box(),+ router_data,+ call_connector_action.clone(),+ connector_request,+ return_raw_connector_response,+ )+ .await?;+ let state_clone = state.clone();+ let router_data_clone = router_data.clone();+ let direct_router_data_clone = direct_router_data.clone();+ let return_raw_connector_response_clone = return_raw_connector_response;+ let context_clone = context.clone();+ tokio::spawn(async move {+ let gateway: Box<dyn PaymentGateway<State, ConnectorData, F, Req, Resp, Context>> =+ F::get_gateway(execution_path);+ let ucs_shadow_result = gateway+ .execute(+ &state_clone,+ connector_integration,+ &router_data_clone,+ call_connector_action,+ None,+ return_raw_connector_response_clone,+ context_clone,+ )+ .await+ .attach_printable("Gateway execution failed");+ // Send comparison data asynchronously+ match ucs_shadow_result {+ Ok(ucs_router_data) => {+ // Send comparison data asynchronously+ if let Some(comparison_service_config) =+ state_clone.get_comparison_service_config()+ {+ let request_id = state_clone.get_request_id_str();+ let _ = helpers::serialize_router_data_and_send_to_comparison_service(+ &state_clone,+ direct_router_data_clone,+ ucs_router_data,+ comparison_service_config,+ request_id,+ )+ .await;+ };+ }+ Err(e) => {+ logger::error!("UCS shadow execution failed: {:?}", e);+ }+ }+ });+ Ok(direct_router_data)+ }+ }+}diff --git a/crates/hyperswitch_interfaces/src/consts.rs b/crates/hyperswitch_interfaces/src/consts.rsindex ec9dc08ae7..f5214b4db7 100644--- a/crates/hyperswitch_interfaces/src/consts.rs+++ b/crates/hyperswitch_interfaces/src/consts.rs@@ -29,3 +29,12 @@ pub const UCS_AUTH_HEADER_KEY: &str = "header-key";/// Header value indicating that currency-auth-key-based authentication is used.pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key";++/// Header value for content type JSON+pub const CONTENT_TYPE: &str = "Content-Type";++/// Header name for flow name+pub const X_FLOW_NAME: &str = "x-flow";++/// Header name for request ID+pub const X_REQUEST_ID: &str = "x-request-id";diff --git a/crates/hyperswitch_interfaces/src/helpers.rs b/crates/hyperswitch_interfaces/src/helpers.rsindex 9bde56eda6..c74f47d03b 100644--- a/crates/hyperswitch_interfaces/src/helpers.rs+++ b/crates/hyperswitch_interfaces/src/helpers.rs@@ -1,3 +1,10 @@+use common_utils::{errors as common_utils_errors, request};+use error_stack::ResultExt;+use hyperswitch_domain_models::router_data;+use masking;+use router_env::{logger, tracing};++use crate::{api_client, consts, errors, types};/// Trait for converting from one foreign type to anotherpub trait ForeignTryFrom<F>: Sized {/// Custom error for conversion failure@@ -5,3 +12,104 @@ pub trait ForeignTryFrom<F>: Sized {/// Convert from a foreign type to the current type and return an error if the conversion failsfn foreign_try_from(from: F) -> Result<Self, Self::Error>;}++/// Data structure to hold comparison data between Hyperswitch and UCS+#[derive(serde::Serialize, Debug)]+pub struct ComparisonData {+ /// Hyperswitch router data+ pub hyperswitch_data: masking::Secret<serde_json::Value>,+ /// Unified Connector Service router data+ pub unified_connector_service_data: masking::Secret<serde_json::Value>,+}++/// Trait to get comparison service configuration+pub trait GetComparisonServiceConfig {+ /// Retrieve the comparison service configuration if available+ fn get_comparison_service_config(&self) -> Option<types::ComparisonServiceConfig>;+}++/// Generic function to serialize router data and send comparison to external service+/// Works for both payments and refunds+pub async fn serialize_router_data_and_send_to_comparison_service<F, RouterDReq, RouterDResp>(+ state: &dyn api_client::ApiClientWrapper,+ hyperswitch_router_data: router_data::RouterData<F, RouterDReq, RouterDResp>,+ unified_connector_service_router_data: router_data::RouterData<F, RouterDReq, RouterDResp>,+ comparison_service_config: types::ComparisonServiceConfig,+ request_id: Option<String>,+) -> common_utils_errors::CustomResult<(), errors::HttpClientError>+where+ F: Send + Clone + Sync + 'static,+ RouterDReq: Send + Sync + Clone + 'static + serde::Serialize,+ RouterDResp: Send + Sync + Clone + 'static + serde::Serialize,+{+ logger::info!("Simulating UCS call for shadow mode comparison");++ let [hyperswitch_data, unified_connector_service_data] = [+ (hyperswitch_router_data, "hyperswitch"),+ (unified_connector_service_router_data, "ucs"),+ ]+ .map(|(data, source)| {+ serde_json::to_value(data)+ .map(masking::Secret::new)+ .unwrap_or_else(|e| {+ masking::Secret::new(serde_json::json!({+ "error": e.to_string(),+ "source": source+ }))+ })+ });++ let comparison_data = ComparisonData {+ hyperswitch_data,+ unified_connector_service_data,+ };+ let _ = send_comparison_data(+ state,+ comparison_data,+ comparison_service_config,+ request_id,+ )+ .await+ .map_err(|e| {+ logger::debug!("Failed to send comparison data: {:?}", e);+ });+ Ok(())+}++/// Sends router data comparison to external service+pub async fn send_comparison_data(+ state: &dyn api_client::ApiClientWrapper,+ comparison_data: ComparisonData,+ comparison_service_config: types::ComparisonServiceConfig,+ request_id: Option<String>,+) -> common_utils_errors::CustomResult<(), errors::HttpClientError> {+ let mut request = request::RequestBuilder::new()+ .method(request::Method::Post)+ .url(comparison_service_config.url.get_string_repr())+ .header(consts::CONTENT_TYPE, "application/json")+ .header(consts::X_FLOW_NAME, "router-data")+ .set_body(request::RequestContent::Json(Box::new(comparison_data)))+ .build();++ if let Some(req_id) = request_id {+ request.add_header(consts::X_REQUEST_ID, masking::Maskable::Normal(req_id));+ }++ let _ = state+ .get_api_client()+ .send_request(+ state,+ request,+ comparison_service_config.timeout_secs,+ false,+ )+ .await+ .inspect_err(|e| {+ tracing::debug!("Error sending comparison data: {:?}", e);+ })+ .change_context(errors::HttpClientError::RequestNotSent(+ "Failed to send comparison data to comparison service".to_string(),+ ))?;++ Ok(())+}diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rsindex 1a0ea2d6db..35e7f5149b 100644--- a/crates/hyperswitch_interfaces/src/types.rs+++ b/crates/hyperswitch_interfaces/src/types.rs@@ -1,5 +1,5 @@//! Types interface-+use common_utils::types::Url;use hyperswitch_domain_models::{router_data::{AccessToken, AccessTokenAuthenticationResponse},router_data_v2::flow_common_types,@@ -86,6 +86,7 @@ use hyperswitch_domain_models::{router_request_types::PayoutsData,router_response_types::PayoutsResponseData,};+use serde;use crate::{api::ConnectorIntegration, connector_integration_v2::ConnectorIntegrationV2};/// struct Response@@ -473,3 +474,17 @@ pub type CreateCustomerTypeV2 = dyn ConnectorIntegrationV2<ConnectorCustomerData,PaymentsResponseData,>;++/// Configuration for the comparison service+///+/// This struct contains configuration parameters for the external comparison service+/// used to compare results between different execution paths (e.g., Direct vs UCS).+#[derive(Debug, serde::Deserialize, Clone)]+pub struct ComparisonServiceConfig {+ /// The URL of the comparison service endpoint+ pub url: Url,+ /// Whether the comparison service is enabled+ pub enabled: bool,+ /// Timeout in seconds for comparison service requests+ pub timeout_secs: Option<u64>,+}diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 0f7a66c01d..1255d8907b 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -7,11 +7,7 @@ use std::{#[cfg(feature = "olap")]use analytics::{opensearch::OpenSearchConfig, ReportConfig};use api_models::enums;-use common_utils::{- ext_traits::ConfigExt,- id_type,- types::{user::EmailThemeConfig, Url},-};+use common_utils::{ext_traits::ConfigExt, id_type, types::user::EmailThemeConfig};use config::{Environment, File};use error_stack::ResultExt;#[cfg(feature = "email")]@@ -34,7 +30,7 @@ pub use hyperswitch_interfaces::{secrets_interface::secret_state::{RawSecret, SecretState, SecretStateContainer, SecuredSecret,},- types::Proxy,+ types::{ComparisonServiceConfig, Proxy},};use masking::Secret;pub use payment_methods::configs::settings::{@@ -209,13 +205,6 @@ pub struct CloneConnectorAllowlistConfig {pub connector_names: HashSet<enums::Connector>,}-#[derive(Debug, Deserialize, Clone)]-pub struct ComparisonServiceConfig {- pub url: Url,- pub enabled: bool,- pub timeout_secs: Option<u64>,-}-#[derive(Debug, Deserialize, Clone, Default)]pub struct Platform {pub enabled: bool,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 8e94397635..2b2099f429 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -2,6 +2,7 @@ pub mod access_token;pub mod conditional_configs;pub mod customers;pub mod flows;+pub mod gateway;pub mod helpers;pub mod operations;@@ -22,9 +23,7 @@ use std::{vec::IntoIter,};-#[cfg(feature = "v2")]use external_services::grpc_client;-#[cfg(feature = "v2")]pub mod payment_methods;@@ -91,6 +90,7 @@ pub use self::operations::{use self::{conditional_configs::perform_decision_management,flows::{ConstructFlowSpecificData, Feature},+ gateway::context as gateway_context,operations::{BoxedOperation, Operation, PaymentResponse},routing::{self as self_routing, SessionFlowRoutingInput},};@@ -149,7 +149,10 @@ use crate::{};#[cfg(feature = "v1")]use crate::{- core::authentication as authentication_core,+ core::{+ authentication as authentication_core,+ unified_connector_service::update_gateway_system_in_feature_metadata,+ },types::{api::authentication, BrowserInformation},};@@ -3984,6 +3987,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(merchant_connector_account: helpers::MerchantConnectorAccountType,mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,tokenization_action: TokenizationAction,+ context: gateway_context::RouterGatewayContext,) -> RouterResult<(RouterData<F, RouterDReq, router_types::PaymentsResponseData>,helpers::MerchantConnectorAccountType,@@ -4146,6 +4150,7 @@ wherebusiness_profile,header_payload.clone(),return_raw_connector_response,+ context,).await} else {@@ -4382,83 +4387,138 @@ where}}- record_time_taken_with(|| async {- match execution_path {- // Process through UCS when system is UCS and not handling response or if it is a UCS webhook action- ExecutionPath::UnifiedConnectorService => {- process_through_ucs(- &updated_state,- req_state,- merchant_context,- operation,- payment_data,- customer,- call_connector_action,- validate_result,- schedule_time,- header_payload,- frm_suggestion,- business_profile,- merchant_connector_account,- &connector,- router_data,- )- .await- }+ let is_ucs_granular_flow =+ gateway::GRANULAR_GATEWAY_SUPPORTED_FLOWS.contains(&std::any::type_name::<F>());- // Process through Direct with Shadow UCS- ExecutionPath::ShadowUnifiedConnectorService => {- process_through_direct_with_shadow_unified_connector_service(- &updated_state,- req_state,- merchant_context,- connector,- operation,- payment_data,- customer,- call_connector_action,- shadow_ucs_call_connector_action,- validate_result,- schedule_time,- header_payload,- frm_suggestion,- business_profile,- is_retry_payment,- all_keys_required,- merchant_connector_account,- router_data,- tokenization_action,- )- .await- }+ if is_ucs_granular_flow {+ logger::info!("Current flow is UCS Composite flow");+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );- // Process through Direct gateway- ExecutionPath::Direct => {- process_through_direct(- state,- req_state,- merchant_context,- connector,- operation,- payment_data,- customer,- call_connector_action,- validate_result,- schedule_time,- header_payload,- frm_suggestion,- business_profile,- is_retry_payment,- all_keys_required,- merchant_connector_account,- router_data,- tokenization_action,- )- .await+ let execution_mode = match execution_path {+ ExecutionPath::UnifiedConnectorService => ExecutionMode::Primary,+ ExecutionPath::ShadowUnifiedConnectorService => ExecutionMode::Shadow,+ // ExecutionMode is irrelevant for Direct path in this context+ ExecutionPath::Direct => ExecutionMode::NotApplicable,+ };++ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path,+ execution_mode,+ };+ // Update feature metadata to track Direct routing usage for stickiness+ update_gateway_system_in_feature_metadata(+ payment_data,+ gateway_context.get_gateway_system(),+ )?;+ call_connector_service(+ state,+ req_state,+ merchant_context,+ connector,+ operation,+ payment_data,+ customer,+ call_connector_action,+ validate_result,+ schedule_time,+ header_payload,+ frm_suggestion,+ business_profile,+ is_retry_payment,+ all_keys_required,+ merchant_connector_account,+ router_data,+ tokenization_action,+ gateway_context,+ )+ .await+ } else {+ record_time_taken_with(|| async {+ match execution_path {+ // Process through UCS when system is UCS and not handling response or if it is a UCS webhook action+ ExecutionPath::UnifiedConnectorService => {+ process_through_ucs(+ &updated_state,+ req_state,+ merchant_context,+ operation,+ payment_data,+ customer,+ call_connector_action,+ validate_result,+ schedule_time,+ header_payload,+ frm_suggestion,+ business_profile,+ merchant_connector_account,+ &connector,+ router_data,+ )+ .await+ }++ // Process through Direct with Shadow UCS+ ExecutionPath::ShadowUnifiedConnectorService => {+ process_through_direct_with_shadow_unified_connector_service(+ &updated_state,+ req_state,+ merchant_context,+ connector,+ operation,+ payment_data,+ customer,+ call_connector_action,+ shadow_ucs_call_connector_action,+ validate_result,+ schedule_time,+ header_payload,+ frm_suggestion,+ business_profile,+ is_retry_payment,+ all_keys_required,+ merchant_connector_account,+ router_data,+ tokenization_action,+ )+ .await+ }++ // Process through Direct gateway+ ExecutionPath::Direct => {+ process_through_direct(+ state,+ req_state,+ merchant_context,+ connector,+ operation,+ payment_data,+ customer,+ call_connector_action,+ validate_result,+ schedule_time,+ header_payload,+ frm_suggestion,+ business_profile,+ is_retry_payment,+ all_keys_required,+ merchant_connector_account,+ router_data,+ tokenization_action,+ )+ .await+ }}- }- })- .await+ })+ .await+ }}async fn record_time_taken_with<F, Fut, R>(f: F) -> RouterResult<R>@@ -4599,6 +4659,19 @@ where// and rely on previous status set in router_data// TODO: status is already set when constructing payment data, why should this be done again?// router_data.status = payment_data.get_payment_attempt().status;+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );+ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account_type_details,+ execution_path: ExecutionPath::Direct,+ execution_mode: ExecutionMode::NotApplicable,+ };router_data.decide_flows(state,@@ -4608,6 +4681,7 @@ wherebusiness_profile,header_payload.clone(),return_raw_connector_response,+ gateway_context,).await} else {@@ -5414,6 +5488,26 @@ where).await?;+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );++ // TODO: determine execution path for proxy call connector service+ let execution_path = ExecutionPath::Direct;+ // Execution mode is irrelevant for Direct execution path+ let execution_mode = ExecutionMode::NotApplicable;++ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path,+ execution_mode,+ };+let router_data = if should_continue_further {// The status of payment_attempt and intent will be updated in the previous step// update this in router_data.@@ -5429,6 +5523,7 @@ wherebusiness_profile,header_payload.clone(),return_raw_connector_response,+ gateway_context,).await} else {@@ -5542,6 +5637,20 @@ whereheader_payload.clone(),).await?;+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );++ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path: ExecutionPath::Direct,+ execution_mode: ExecutionMode::NotApplicable,+ };let router_data = if should_continue_further {router_data@@ -5553,6 +5662,7 @@ wherebusiness_profile,header_payload.clone(),return_raw_connector_response,+ gateway_context,).await} else {@@ -5667,6 +5777,20 @@ whereheader_payload.clone(),).await?;+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );++ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path: ExecutionPath::Direct,+ execution_mode: ExecutionMode::NotApplicable,+ };let router_data = if should_continue_further {router_data@@ -5678,6 +5802,7 @@ wherebusiness_profile,header_payload.clone(),return_raw_connector_response,+ gateway_context,).await} else {@@ -6202,6 +6327,19 @@ whereSome(header_payload.clone()),).await?;+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );+ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path: ExecutionPath::Direct,+ execution_mode: ExecutionMode::NotApplicable,+ };let res = router_data.decide_flows(state,@@ -6211,6 +6349,7 @@ wherebusiness_profile,header_payload.clone(),return_raw_connector_response,+ gateway_context,);join_handlers.push(res);@@ -6327,6 +6466,25 @@ where).await?;+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );++ // TODO: determine execution path for SDK session token call.+ let execution_path = ExecutionPath::Direct;+ let execution_mode = ExecutionMode::NotApplicable;++ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path,+ execution_mode,+ };+let res = router_data.decide_flows(state,&session_connector_data.connector,@@ -6335,6 +6493,7 @@ wherebusiness_profile,header_payload.clone(),return_raw_connector_response,+ gateway_context,);join_handlers.push(res);diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rsindex b70cef74db..12255441c1 100644--- a/crates/router/src/core/payments/flows.rs+++ b/crates/router/src/core/payments/flows.rs@@ -32,7 +32,7 @@ use hyperswitch_interfaces::api as api_interfaces;use crate::{core::{errors::{ApiErrorResponse, RouterResult},- payments::{self, helpers},+ payments::{self, gateway::context as gateway_context, helpers},},logger,routes::SessionState,@@ -92,6 +92,7 @@ pub trait Feature<F, T> {business_profile: &domain::Profile,header_payload: domain_payments::HeaderPayload,return_raw_connector_response: Option<bool>,+ gateway_context: gateway_context::RouterGatewayContext,) -> RouterResult<Self>whereSelf: Sized,@@ -324,6 +325,7 @@ pub async fn call_capture_request(call_connector_action: payments::CallConnectorAction,business_profile: &domain::Profile,header_payload: domain_payments::HeaderPayload,+ context: gateway_context::RouterGatewayContext,) -> RouterResult<types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>>{// Build capture-specific connector request@@ -341,6 +343,7 @@ pub async fn call_capture_request(business_profile,header_payload.clone(),None,+ context, // gateway_context).await}diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rsindex 87486f3977..3bf3ea9aa4 100644--- a/crates/router/src/core/payments/flows/approve_flow.rs+++ b/crates/router/src/core/payments/flows/approve_flow.rs@@ -4,7 +4,9 @@ use super::{ConstructFlowSpecificData, Feature};use crate::{core::{errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},- payments::{self, access_token, helpers, transformers, PaymentData},+ payments::{+ self, access_token, flows::gateway_context, helpers, transformers, PaymentData,+ },},routes::SessionState,services,@@ -75,6 +77,7 @@ impl Feature<api::Approve, types::PaymentsApproveData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: gateway_context::RouterGatewayContext,) -> RouterResult<Self> {Err(ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("Flow not supported".to_string()),diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex c231a24593..5bb9763ae7 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -24,7 +24,8 @@ use crate::{errors::{ConnectorErrorExt, RouterResult},mandate,payments::{- self, access_token, customers, helpers, tokenization, transformers, PaymentData,+ self, access_token, customers, flows::gateway_context, helpers, tokenization,+ transformers, PaymentData,},unified_connector_service::{self, build_unified_connector_service_auth_metadata,@@ -203,6 +204,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAubusiness_profile: &domain::Profile,header_payload: domain_payments::HeaderPayload,return_raw_connector_response: Option<bool>,+ gateway_context: gateway_context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::Authorize,@@ -250,6 +252,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAucall_connector_action.clone(),business_profile,header_payload,+ gateway_context,)).await?;}@@ -873,6 +876,7 @@ impl<F>}}+#[allow(clippy::too_many_arguments)]async fn process_capture_flow(mut router_data: types::RouterData<api::Authorize,@@ -885,6 +889,7 @@ async fn process_capture_flow(call_connector_action: payments::CallConnectorAction,business_profile: &domain::Profile,header_payload: domain_payments::HeaderPayload,+ context: gateway_context::RouterGatewayContext,) -> RouterResult<types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>,> {@@ -903,6 +908,7 @@ async fn process_capture_flow(call_connector_action,business_profile,header_payload,+ context,).await;diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rsindex f1f6d7ddc2..f8105d2ef4 100644--- a/crates/router/src/core/payments/flows/cancel_flow.rs+++ b/crates/router/src/core/payments/flows/cancel_flow.rs@@ -99,6 +99,7 @@ impl Feature<api::Void, types::PaymentsCancelData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {metrics::PAYMENT_CANCEL_COUNT.add(1,diff --git a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rsindex 0ac493c56c..816f4e3c9d 100644--- a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs+++ b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs@@ -82,6 +82,7 @@ impl Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {metrics::PAYMENT_CANCEL_COUNT.add(1,diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rsindex f8738ccd04..56f2353421 100644--- a/crates/router/src/core/payments/flows/capture_flow.rs+++ b/crates/router/src/core/payments/flows/capture_flow.rs@@ -106,6 +106,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::Capture,diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 4b4c75ff78..3aa66de70f 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -107,6 +107,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>business_profile: &domain::Profile,header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ gateway_context: payments::flows::gateway_context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::CompleteAuthorize,@@ -143,6 +144,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>call_connector_action.clone(),business_profile,header_payload,+ gateway_context,)).await?;}@@ -951,6 +953,7 @@ async fn call_unified_connector_service_complete_authorize(Ok(())}+#[allow(clippy::too_many_arguments)]async fn process_capture_flow(mut router_data: types::RouterData<api::CompleteAuthorize,@@ -963,6 +966,7 @@ async fn process_capture_flow(call_connector_action: payments::CallConnectorAction,business_profile: &domain::Profile,header_payload: hyperswitch_domain_models::payments::HeaderPayload,+ gateway_context: payments::flows::gateway_context::RouterGatewayContext,) -> RouterResult<types::RouterData<api::CompleteAuthorize,@@ -985,6 +989,7 @@ async fn process_capture_flow(call_connector_action,business_profile,header_payload,+ gateway_context,).await;diff --git a/crates/router/src/core/payments/flows/extend_authorization_flow.rs b/crates/router/src/core/payments/flows/extend_authorization_flow.rsindex f67500ea9f..35ba0d90b1 100644--- a/crates/router/src/core/payments/flows/extend_authorization_flow.rs+++ b/crates/router/src/core/payments/flows/extend_authorization_flow.rs@@ -82,6 +82,7 @@ impl Feature<api::ExtendAuthorization, types::PaymentsExtendAuthorizationData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {metrics::PAYMENT_EXTEND_AUTHORIZATION_COUNT.add(1,diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rsindex a39cf5aac3..615d4fe47f 100644--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs@@ -20,7 +20,8 @@ use crate::{errors::{ConnectorErrorExt, RouterResult},mandate,payments::{- self, access_token, customers, helpers, tokenization, transformers, PaymentData,+ self, access_token, customers, gateway::context as gateway_context, helpers,+ tokenization, transformers, PaymentData,},unified_connector_service::{self, ucs_logging_wrapper},},@@ -88,6 +89,7 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>business_profile: &domain::Profile,header_payload: domain_payments::HeaderPayload,return_raw_connector_response: Option<bool>,+ gateway_context: gateway_context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::ExternalVaultProxy,diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rsindex 21d275b730..8c23dc9529 100644--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs@@ -82,6 +82,7 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::IncrementalAuthorization,diff --git a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs b/crates/router/src/core/payments/flows/post_session_tokens_flow.rsindex 089dca99cd..a608c9f11c 100644--- a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs+++ b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs@@ -82,6 +82,7 @@ impl Feature<api::PostSessionTokens, types::PaymentsPostSessionTokensData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::PostSessionTokens,diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rsindex e620b35483..923e771e01 100644--- a/crates/router/src/core/payments/flows/psync_flow.rs+++ b/crates/router/src/core/payments/flows/psync_flow.rs@@ -6,9 +6,12 @@ use common_utils::{id_type, types::MinorUnit, ucs_types};use error_stack::ResultExt;use external_services::grpc_client;use hyperswitch_domain_models::payments as domain_payments;-use hyperswitch_interfaces::unified_connector_service::{- get_payments_response_from_ucs_webhook_content,- handle_unified_connector_service_response_for_payment_get,+use hyperswitch_interfaces::{+ api::gateway,+ unified_connector_service::{+ get_payments_response_from_ucs_webhook_content,+ handle_unified_connector_service_response_for_payment_get,+ },};use unified_connector_service_client::payments as payments_grpc;use unified_connector_service_masking::ExposeInterface;@@ -111,6 +114,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>_business_profile: &domain::Profile,_header_payload: domain_payments::HeaderPayload,return_raw_connector_response: Option<bool>,+ gateway_context: payments::flows::gateway_context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::PSync,@@ -134,6 +138,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>call_connector_action,connector_integration,return_raw_connector_response,+ gateway_context,).await?;// Initiating Integrity checks@@ -149,13 +154,14 @@ impl Feature<api::PSync, types::PaymentsSyncData>(types::SyncRequestType::MultipleCaptureSync(_), Err(err)) => Err(err),_ => {// for bulk sync of captures, above logic needs to be handled at connector end- let mut new_router_data = services::execute_connector_processing_step(+ let mut new_router_data = gateway::execute_payment_gateway(state,connector_integration,&self,call_connector_action,connector_request,return_raw_connector_response,+ gateway_context,).await.to_payment_failed_response()?;@@ -459,15 +465,16 @@ where{async fn execute_connector_processing_step_for_each_capture(&self,- _state: &SessionState,- _pending_connector_capture_id_list: Vec<String>,- _call_connector_action: payments::CallConnectorAction,- _connector_integration: services::BoxedPaymentConnectorIntegrationInterface<+ state: &SessionState,+ pending_connector_capture_id_list: Vec<String>,+ call_connector_action: payments::CallConnectorAction,+ connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::PSync,types::PaymentsSyncData,types::PaymentsResponseData,>,- _return_raw_connector_response: Option<bool>,+ return_raw_connector_response: Option<bool>,+ gateway_context: payments::flows::gateway_context::RouterGatewayContext,) -> RouterResult<Self>;}@@ -486,6 +493,7 @@ impl RouterDataPSynctypes::PaymentsResponseData,>,return_raw_connector_response: Option<bool>,+ gateway_context: payments::flows::gateway_context::RouterGatewayContext,) -> RouterResult<Self> {let mut capture_sync_response_map = HashMap::new();if let payments::CallConnectorAction::HandleResponse(_) = call_connector_action {@@ -509,13 +517,14 @@ impl RouterDataPSynclet mut cloned_router_data = self.clone();cloned_router_data.request.connector_transaction_id =types::ResponseId::ConnectorTransactionId(connector_capture_id.clone());- let resp = services::execute_connector_processing_step(+ let resp = gateway::execute_payment_gateway(state,connector_integration.clone_box(),&cloned_router_data,call_connector_action.clone(),None,return_raw_connector_response,+ gateway_context.clone(),).await.to_payment_failed_response()?;diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rsindex 5c6fb58ce1..62a132962d 100644--- a/crates/router/src/core/payments/flows/reject_flow.rs+++ b/crates/router/src/core/payments/flows/reject_flow.rs@@ -74,6 +74,7 @@ impl Feature<api::Reject, types::PaymentsRejectData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {Err(ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("Flow not supported".to_string()),diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rsindex 3356ccf667..ee5337cb1f 100644--- a/crates/router/src/core/payments/flows/session_flow.rs+++ b/crates/router/src/core/payments/flows/session_flow.rs@@ -106,6 +106,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessiobusiness_profile: &domain::Profile,header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {metrics::SESSION_TOKEN_CREATED.add(1,diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rsindex 06db8ba7d0..bd35e60c05 100644--- a/crates/router/src/core/payments/flows/session_update_flow.rs+++ b/crates/router/src/core/payments/flows/session_update_flow.rs@@ -80,6 +80,7 @@ impl Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::SdkSessionUpdate,diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rsindex 82880fb97c..0cf4c92375 100644--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs@@ -119,6 +119,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup_business_profile: &domain::Profile,_header_payload: domain_payments::HeaderPayload,_return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::SetupMandate,diff --git a/crates/router/src/core/payments/flows/update_metadata_flow.rs b/crates/router/src/core/payments/flows/update_metadata_flow.rsindex 10ec980455..a223b58816 100644--- a/crates/router/src/core/payments/flows/update_metadata_flow.rs+++ b/crates/router/src/core/payments/flows/update_metadata_flow.rs@@ -79,6 +79,7 @@ impl Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData>_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,return_raw_connector_response: Option<bool>,+ _gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<api::UpdateMetadata,diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rsnew file mode 100644index 0000000000..564dbaa1f3--- /dev/null+++ b/crates/router/src/core/payments/gateway.rs@@ -0,0 +1,9 @@+pub mod context;+pub mod psync_gateway;++use std::sync;++use hyperswitch_domain_models::router_flow_types::payments;++pub static GRANULAR_GATEWAY_SUPPORTED_FLOWS: sync::LazyLock<Vec<&'static str>> =+ sync::LazyLock::new(|| vec![std::any::type_name::<payments::PSync>()]);diff --git a/crates/router/src/core/payments/gateway/context.rs b/crates/router/src/core/payments/gateway/context.rsnew file mode 100644index 0000000000..14d1dd57cc--- /dev/null+++ b/crates/router/src/core/payments/gateway/context.rs@@ -0,0 +1,94 @@+//! Gateway execution context for router crate+//!+//! This module defines the RouterGatewayContext type, which contains all the+//! information needed for executing payment operations through either direct+//! connector integration or Unified Connector Service (UCS).++use common_enums::{ExecutionMode, ExecutionPath, GatewaySystem};+use external_services::grpc_client::LineageIds;+use hyperswitch_domain_models::{merchant_context::MerchantContext, payments::HeaderPayload};+use hyperswitch_interfaces::api::gateway::GatewayContext;++use crate::core::payments::helpers;++/// Router's gateway execution context+///+/// This is the router crate's implementation of gateway context. It contains+/// all the information needed for both direct connector execution and UCS execution.+#[derive(Clone, Debug)]+pub struct RouterGatewayContext {+ pub creds_identifier: Option<String>,+ /// Merchant context (merchant_id, profile_id, etc.)+ pub merchant_context: MerchantContext,++ /// Header payload (x-reference-id, etc.)+ pub header_payload: HeaderPayload,++ /// Lineage IDs for distributed tracing+ pub lineage_ids: LineageIds,++ /// Merchant connector account details+ #[cfg(feature = "v1")]+ pub merchant_connector_account: helpers::MerchantConnectorAccountType,++ /// Merchant connector account details (v2)+ #[cfg(feature = "v2")]+ pub merchant_connector_account:+ hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountTypeDetails,++ /// Execution mode (Primary, Shadow, etc.)+ pub execution_mode: ExecutionMode,++ /// Execution path (Direct, UCS, or Shadow)+ pub execution_path: ExecutionPath,+}++impl RouterGatewayContext {+ /// Create a new router gateway context+ pub fn new(+ merchant_context: MerchantContext,+ header_payload: HeaderPayload,+ lineage_ids: LineageIds,+ #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,+ #[cfg(feature = "v2")]+ merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountTypeDetails,+ execution_mode: ExecutionMode,+ execution_path: ExecutionPath,+ creds_identifier: Option<String>,+ ) -> Self {+ Self {+ merchant_context,+ header_payload,+ lineage_ids,+ merchant_connector_account,+ execution_mode,+ execution_path,+ creds_identifier,+ }+ }+}++/// Implementation of GatewayContext trait for RouterGatewayContext+///+/// This allows the framework to extract execution metadata without knowing+/// the concrete structure of RouterGatewayContext.+impl GatewayContext for RouterGatewayContext {+ fn execution_path(&self) -> ExecutionPath {+ self.execution_path+ }++ /// Get the execution mode (Primary, Shadow, etc.)+ fn execution_mode(&self) -> ExecutionMode {+ self.execution_mode+ }+}+impl RouterGatewayContext {+ /// Get the gateway system (Direct, UnifiedConnectorService, etc.)+ pub fn get_gateway_system(&self) -> GatewaySystem {+ match self.execution_path {+ ExecutionPath::Direct => GatewaySystem::Direct,+ ExecutionPath::UnifiedConnectorService => GatewaySystem::UnifiedConnectorService,+ ExecutionPath::ShadowUnifiedConnectorService => GatewaySystem::Direct,+ }+ }+}diff --git a/crates/router/src/core/payments/gateway/psync_gateway.rs b/crates/router/src/core/payments/gateway/psync_gateway.rsnew file mode 100644index 0000000000..7e08219e15--- /dev/null+++ b/crates/router/src/core/payments/gateway/psync_gateway.rs@@ -0,0 +1,242 @@+use std::str::FromStr;++use async_trait::async_trait;+use common_enums::{CallConnectorAction, ExecutionPath};+use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};+use error_stack::ResultExt;+use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};+use hyperswitch_interfaces::{+ api::gateway as payment_gateway,+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},+ errors::ConnectorError,+ unified_connector_service::handle_unified_connector_service_response_for_payment_get,+};+use unified_connector_service_client::payments as payments_grpc;+use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;++use crate::{+ core::{payments::gateway::context::RouterGatewayContext, unified_connector_service},+ routes::SessionState,+ services::logger,+ types::{self, transformers::ForeignTryFrom, MinorUnit},+};++// =============================================================================+// PaymentGateway Implementation for domain::PSync+// =============================================================================++/// Implementation of PaymentGateway for api::PSync flow+#[async_trait]+impl<RCD>+ payment_gateway::PaymentGateway<+ SessionState,+ RCD,+ Self,+ types::PaymentsSyncData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ > for domain::PSync+where+ RCD: Clone+ + Send+ + Sync+ + 'static+ + RouterDataConversion<Self, types::PaymentsSyncData, types::PaymentsResponseData>,+{+ async fn execute(+ self: Box<Self>,+ state: &SessionState,+ _connector_integration: BoxedConnectorIntegrationInterface<+ Self,+ RCD,+ types::PaymentsSyncData,+ types::PaymentsResponseData,+ >,+ router_data: &RouterData<Self, types::PaymentsSyncData, types::PaymentsResponseData>,+ call_connector_action: CallConnectorAction,+ _connector_request: Option<Request>,+ _return_raw_connector_response: Option<bool>,+ context: RouterGatewayContext,+ ) -> CustomResult<+ RouterData<Self, types::PaymentsSyncData, types::PaymentsResponseData>,+ ConnectorError,+ > {+ let connector_name = router_data.connector.clone();+ let connector_enum = common_enums::connector_enums::Connector::from_str(&connector_name)+ .change_context(ConnectorError::InvalidConnectorName)?;+ let merchant_connector_account = context.merchant_connector_account;+ let creds_identifier = context.creds_identifier;+ let merchant_context = context.merchant_context;+ let lineage_ids = context.lineage_ids;+ let header_payload = context.header_payload;+ let unified_connector_service_execution_mode = context.execution_mode;+ let merchant_order_reference_id = header_payload.x_reference_id.clone();+ let is_ucs_psync_disabled = state+ .conf+ .grpc_client+ .unified_connector_service+ .as_ref()+ .is_some_and(|config| {+ config+ .ucs_psync_disabled_connectors+ .contains(&connector_enum)+ });++ if is_ucs_psync_disabled {+ logger::info!(+ "UCS PSync call disabled for connector: {}, skipping UCS call",+ connector_name+ );+ return Ok(router_data.clone());+ }+ let client = state+ .grpc_client+ .unified_connector_service_client+ .clone()+ .ok_or(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to fetch Unified Connector Service client")?;++ let payment_get_request = payments_grpc::PaymentServiceGetRequest::foreign_try_from((+ router_data,+ call_connector_action,+ ))+ .change_context(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct Payment Get Request")?;++ let merchant_connector_id = merchant_connector_account.get_mca_id();++ let connector_auth_metadata =+ unified_connector_service::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ &merchant_context,+ )+ .change_context(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct request metadata")?;+ let merchant_reference_id = header_payload+ .x_reference_id+ .clone()+ .or(merchant_order_reference_id)+ .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))+ .transpose()+ .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))+ .ok()+ .flatten()+ .map(ucs_types::UcsReferenceId::Payment);+ let header_payload = state+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .lineage_ids(lineage_ids);+ let connector_name = router_data.connector.clone();+ let updated_router_data = Box::pin(unified_connector_service::ucs_logging_wrapper_new(+ router_data.clone(),+ state,+ payment_get_request,+ header_payload,+ |mut router_data, payment_get_request, grpc_headers| async move {+ let response = client+ .payment_get(payment_get_request, connector_auth_metadata, grpc_headers)+ .await+ .attach_printable("Failed to get payment")?;++ let payment_get_response = response.into_inner();++ let (router_data_response, status_code) =+ handle_unified_connector_service_response_for_payment_get(+ payment_get_response.clone(),+ )+ .attach_printable("Failed to deserialize UCS response")?;++ // Extract and store access token if present+ if let Some(access_token) =+ unified_connector_service::get_access_token_from_ucs_response(+ state,+ &merchant_context,+ &connector_name,+ merchant_connector_id.as_ref(),+ creds_identifier.clone(),+ payment_get_response.state.as_ref(),+ )+ .await+ {+ if let Err(error) = unified_connector_service::set_access_token_for_ucs(+ state,+ &merchant_context,+ &connector_name,+ access_token,+ merchant_connector_id.as_ref(),+ creds_identifier,+ )+ .await+ {+ logger::error!(+ ?error,+ "Failed to store UCS access token from psync response"+ );+ } else {+ logger::debug!("Successfully stored access token from UCS psync response");+ }+ }++ let router_data_response = router_data_response.map(|(response, status)| {+ router_data.status = status;+ response+ });+ router_data.response = router_data_response;+ router_data.amount_captured = payment_get_response.captured_amount;+ router_data.minor_amount_captured = payment_get_response+ .minor_captured_amount+ .map(MinorUnit::new);+ 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);++ Ok((router_data, payment_get_response))+ },+ ))+ .await+ .change_context(ConnectorError::ResponseHandlingFailed)?;++ Ok(updated_router_data)+ }+}++/// Implementation of FlowGateway for api::PSync+///+/// This allows the flow to provide its specific gateway based on execution path+impl<RCD>+ payment_gateway::FlowGateway<+ SessionState,+ RCD,+ types::PaymentsSyncData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ > for domain::PSync+where+ RCD: Clone+ + Send+ + Sync+ + 'static+ + RouterDataConversion<Self, types::PaymentsSyncData, types::PaymentsResponseData>,+{+ fn get_gateway(+ execution_path: ExecutionPath,+ ) -> Box<+ dyn payment_gateway::PaymentGateway<+ SessionState,+ RCD,+ Self,+ types::PaymentsSyncData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ >,+ > {+ match execution_path {+ ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),+ ExecutionPath::UnifiedConnectorService+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),+ }+ }+}diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex efd5f5599f..dc8a7ad415 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -12,7 +12,7 @@ use api_models::{};use base64::Engine;#[cfg(feature = "v1")]-use common_enums::enums::{CallConnectorAction, ExecutionMode, GatewaySystem};+use common_enums::enums::{CallConnectorAction, ExecutionMode, ExecutionPath, GatewaySystem};use common_enums::ConnectorType;#[cfg(feature = "v2")]use common_utils::id_type::GenerateId;@@ -77,6 +77,7 @@ use crate::core::{payments::{call_connector_service, customers,flows::{ConstructFlowSpecificData, Feature},+ gateway::context as gateway_context,operations::ValidateResult as OperationsValidateResult,should_add_task_to_process_tracker, OperationSessionGetters, OperationSessionSetters,TokenizationAction,@@ -8507,6 +8508,19 @@ where// Update feature metadata to track Direct routing usage for stickinessupdate_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?;+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),+ );+ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: None,+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path: ExecutionPath::Direct,+ execution_mode: ExecutionMode::NotApplicable,+ };call_connector_service(state,@@ -8527,6 +8541,7 @@ wheremerchant_connector_account,router_data,tokenization_action,+ gateway_context,).await}@@ -8615,6 +8630,17 @@ where// Update feature metadata to track Direct routing usage for stickinessupdate_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?;+ let execution_mode = ExecutionMode::NotApplicable;++ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ merchant_context: merchant_context.clone(),+ header_payload: header_payload.clone(),+ lineage_ids: lineage_ids.clone(),+ merchant_connector_account: merchant_connector_account.clone(),+ execution_path: ExecutionPath::Direct,+ execution_mode,+ };// Call Direct connector servicelet result = call_connector_service(@@ -8636,6 +8662,7 @@ wheremerchant_connector_account,router_data,tokenization_action,+ gateway_context,).await?;diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex f8ad03156f..77335d9c8b 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1614,6 +1614,139 @@ where})}+/// new UCS Event Logging Wrapper Function with UCS error response+/// This function wraps UCS calls with comprehensive event logging.+/// It logs the actual gRPC request/response data, timing, and error information.+#[instrument(skip_all, fields(connector_name, flow_type, payment_id))]+pub async fn ucs_logging_wrapper_new<T, F, Fut, Req, Resp, GrpcReq, GrpcResp>(+ router_data: RouterData<T, Req, Resp>,+ state: &SessionState,+ grpc_request: GrpcReq,+ grpc_header_builder: external_services::grpc_client::GrpcHeadersUcsBuilderFinal,+ handler: F,+) -> CustomResult<RouterData<T, Req, Resp>, UnifiedConnectorServiceError>+where+ T: std::fmt::Debug + Clone + Send + 'static,+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,+ GrpcReq: serde::Serialize,+ GrpcResp: serde::Serialize,+ F: FnOnce(+ RouterData<T, Req, Resp>,+ GrpcReq,+ external_services::grpc_client::GrpcHeadersUcs,+ ) -> Fut+ + Send,+ Fut: std::future::Future<+ Output = CustomResult<+ (RouterData<T, Req, Resp>, GrpcResp),+ UnifiedConnectorServiceError,+ >,+ > + Send,+{+ tracing::Span::current().record("connector_name", &router_data.connector);+ tracing::Span::current().record("flow_type", std::any::type_name::<T>());+ tracing::Span::current().record("payment_id", &router_data.payment_id);++ // Capture request data for logging+ let connector_name = router_data.connector.clone();+ let payment_id = router_data.payment_id.clone();+ let merchant_id = router_data.merchant_id.clone();+ let refund_id = router_data.refund_id.clone();+ let dispute_id = router_data.dispute_id.clone();+ let grpc_header = grpc_header_builder.build();+ // Log the actual gRPC request with masking+ let grpc_request_body = masking::masked_serialize(&grpc_request)+ .unwrap_or_else(|_| serde_json::json!({"error": "failed_to_serialize_grpc_request"}));++ // Update connector call count metrics for UCS operations+ crate::routes::metrics::CONNECTOR_CALL_COUNT.add(+ 1,+ router_env::metric_attributes!(+ ("connector", connector_name.clone()),+ (+ "flow",+ std::any::type_name::<T>()+ .split("::")+ .last()+ .unwrap_or_default()+ ),+ ),+ );++ // Execute UCS function and measure timing+ let start_time = Instant::now();+ let result = handler(router_data, grpc_request, grpc_header).await;+ let external_latency = start_time.elapsed().as_millis();++ // Create and emit connector event after UCS call+ let (status_code, response_body, router_result) = match result {+ Ok((updated_router_data, grpc_response)) => {+ let status = updated_router_data+ .connector_http_status_code+ .unwrap_or(200);++ // Log the actual gRPC response+ let grpc_response_body = serde_json::to_value(&grpc_response).unwrap_or_else(+ |_| serde_json::json!({"error": "failed_to_serialize_grpc_response"}),+ );++ (status, Some(grpc_response_body), Ok(updated_router_data))+ }+ 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(),)),+ );++ let error_body = serde_json::json!({+ "error": error.to_string(),+ "error_type": "ucs_call_failed"+ });+ (500, Some(error_body), Err(error))+ }+ };++ let mut connector_event = ConnectorEvent::new(+ state.tenant.tenant_id.clone(),+ connector_name,+ std::any::type_name::<T>(),+ grpc_request_body,+ "grpc://unified-connector-service".to_string(),+ Method::Post,+ payment_id,+ merchant_id,+ state.request_id.as_ref(),+ external_latency,+ refund_id,+ dispute_id,+ status_code,+ );++ // Set response body based on status code+ if let Some(body) = response_body {+ match status_code {+ 400..=599 => {+ connector_event.set_error_response_body(&body);+ }+ _ => {+ connector_event.set_response_body(&body);+ }+ }+ }++ // Emit event+ state.event_handler.log_event(&connector_event);++ // Set external latency on router data+ router_result.map(|mut router_data| {+ router_data.external_latency =+ Some(router_data.external_latency.unwrap_or(0) + external_latency);+ router_data+ })+}+#[derive(serde::Serialize)]pub struct ComparisonData {pub hyperswitch_data: Secret<serde_json::Value>,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex a655d44a35..06a3b8bd06 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -23,7 +23,9 @@ use external_services::{use hyperswitch_interfaces::{crm::CrmInterface,encryption_interface::EncryptionManagementInterface,+ helpers as interfaces_helpers,secrets_interface::secret_state::{RawSecret, SecuredSecret},+ types as interfaces_types,};use router_env::RequestId;use scheduler::SchedulerInterface;@@ -164,13 +166,14 @@ impl SessionState {let tenant_id = self.tenant.tenant_id.get_string_repr().to_string();let request_id = self.request_id.clone();let shadow_mode = match unified_connector_service_execution_mode {- ExecutionMode::Primary => false,- ExecutionMode::Shadow => true,+ ExecutionMode::Primary => Some(false),+ ExecutionMode::Shadow => Some(true),+ ExecutionMode::NotApplicable => None,};GrpcHeadersUcs::builder().tenant_id(tenant_id).request_id(request_id)- .shadow_mode(Some(shadow_mode))+ .shadow_mode(shadow_mode)}#[cfg(all(feature = "revenue_recovery", feature = "v2"))]pub fn get_recovery_grpc_headers(&self) -> GrpcRecoveryHeaders {@@ -251,6 +254,12 @@ impl SessionStateInfo for SessionState {}}+impl interfaces_helpers::GetComparisonServiceConfig for SessionState {+ fn get_comparison_service_config(&self) -> Option<interfaces_types::ComparisonServiceConfig> {+ self.conf.comparison_service.clone()+ }+}+impl hyperswitch_interfaces::api_client::ApiClientWrapper for SessionState {fn get_api_client(&self) -> &dyn crate::services::ApiClient {self.api_client.as_ref()