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(disputes): route actions through UCS tunnel (#15035)
Amitsingh Tanwar9dc20778bfea
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex f774348543..fc19d95bae 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -1237,6 +1237,112 @@ impl UnifiedConnectorServiceClient {})}+ /// Accepts (concedes) a dispute via DisputeService.Accept+ pub async fn dispute_accept(+ &self,+ dispute_accept_request: payments_grpc::DisputeServiceAcceptRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::DisputeServiceAcceptResponse>>+ {+ let mut request = tonic::Request::new(dispute_accept_request);++ let connector_name = connector_auth_metadata.connector_name.clone();+ let metadata =+ build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;+ *request.metadata_mut() = metadata;++ self.dispute_service_client+ .clone()+ .accept(request)+ .await+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ })+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="dispute_accept",+ connector_name=?connector_name,+ "UCS dispute accept gRPC call failed"+ )+ })+ }++ /// Submits dispute evidence via DisputeService.SubmitEvidence+ pub async fn dispute_submit_evidence(+ &self,+ dispute_submit_evidence_request: payments_grpc::DisputeServiceSubmitEvidenceRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<+ tonic::Response<payments_grpc::DisputeServiceSubmitEvidenceResponse>,+ > {+ let mut request = tonic::Request::new(dispute_submit_evidence_request);++ let connector_name = connector_auth_metadata.connector_name.clone();+ let metadata =+ build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;+ *request.metadata_mut() = metadata;++ self.dispute_service_client+ .clone()+ .submit_evidence(request)+ .await+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ })+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="dispute_submit_evidence",+ connector_name=?connector_name,+ "UCS dispute submit evidence gRPC call failed"+ )+ })+ }++ /// Defends a dispute via DisputeService.Defend+ pub async fn dispute_defend(+ &self,+ dispute_defend_request: payments_grpc::DisputeServiceDefendRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::DisputeServiceDefendResponse>>+ {+ let mut request = tonic::Request::new(dispute_defend_request);++ let connector_name = connector_auth_metadata.connector_name.clone();+ let metadata =+ build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;+ *request.metadata_mut() = metadata;++ self.dispute_service_client+ .clone()+ .defend(request)+ .await+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ })+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="dispute_defend",+ connector_name=?connector_name,+ "UCS dispute defend gRPC call failed"+ )+ })+ }+/// Performs Payout Createpub async fn payout_create(&self,diff --git a/crates/hyperswitch_interfaces/src/api/gateway.rs b/crates/hyperswitch_interfaces/src/api/gateway.rsindex 53dab4ddc1..d7660ba1a2 100644--- a/crates/hyperswitch_interfaces/src/api/gateway.rs+++ b/crates/hyperswitch_interfaces/src/api/gateway.rs@@ -14,7 +14,10 @@ use common_utils::{request::Request,};use error_stack::{Report, ResultExt};-use hyperswitch_domain_models::router_data::RouterData;+use hyperswitch_domain_models::{+ errors::api_error_response::ApiErrorResponse, router_data::RouterData,+};+use hyperswitch_masking::Secret;use router_env::{logger, tracing::Instrument};use crate::{@@ -612,6 +615,152 @@ where}}+/// A dispute action executed through the direct connector or UCS.+#[async_trait]+pub trait DisputeGateway<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 one dispute action through this gateway implementation.+ async fn execute(+ self: Box<Self>,+ state: &State,+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,+ router_data: &RouterData<F, Req, Resp>,+ context: Context,+ ) -> CustomResult<RouterData<F, Req, Resp>, ApiErrorResponse>;+}++/// Selects the gateway implementation for a dispute flow.+pub trait DisputeFlowGateway<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,+{+ /// Select the direct or UCS gateway for this dispute flow.+ fn get_dispute_gateway(+ execution_path: ExecutionPath,+ ) -> Box<dyn DisputeGateway<State, ConnectorData, Self, Req, Resp, Context>>;+}++fn dispute_comparison_value<F, Req, Resp>(+ result: &CustomResult<RouterData<F, Req, Resp>, ApiErrorResponse>,+) -> serde_json::Value+where+ Resp: std::fmt::Debug,+{+ match result {+ Ok(data) => serde_json::json!({+ "connector_http_status_code": data.connector_http_status_code,+ "response": format!("{:?}", data.response),+ }),+ Err(error) => serde_json::json!({ "error": format!("{error:?}") }),+ }+}++/// Run a dispute through the selected gateway. The shadow path returns the direct result+/// and compares only outcomes, keeping dispute evidence out of the comparison payload.+pub async fn execute_dispute_gateway<State, ConnectorData, F, Req, Resp, Context>(+ state: &State,+ ucs_state: &State,+ connector_integration: BoxedConnectorIntegrationInterface<F, ConnectorData, Req, Resp>,+ router_data: &RouterData<F, Req, Resp>,+ context: Context,+) -> CustomResult<RouterData<F, Req, Resp>, ApiErrorResponse>+where+ State: Clone + Send + Sync + 'static + ApiClientWrapper + helpers::GetComparisonServiceConfig,+ ConnectorData: Clone + RouterDataConversion<F, Req, Resp> + Send + Sync + 'static,+ F: DisputeFlowGateway<State, ConnectorData, Req, Resp, Context>,+ Req: std::fmt::Debug + Clone + Send + Sync + 'static,+ Resp: std::fmt::Debug + Clone + Send + Sync + 'static,+ Context: GatewayContext + 'static,+{+ match context.execution_path() {+ ExecutionPath::Direct => {+ F::get_dispute_gateway(ExecutionPath::Direct)+ .execute(state, connector_integration, router_data, context)+ .await+ }+ ExecutionPath::UnifiedConnectorService => {+ F::get_dispute_gateway(ExecutionPath::UnifiedConnectorService)+ .execute(ucs_state, connector_integration, router_data, context)+ .await+ }+ ExecutionPath::ShadowUnifiedConnectorService => {+ let direct_result = F::get_dispute_gateway(ExecutionPath::Direct)+ .execute(+ state,+ connector_integration.clone_box(),+ router_data,+ context.clone(),+ )+ .await;+ let direct_for_compare = dispute_comparison_value(&direct_result);+ let shadow_state = ucs_state.clone();+ let shadow_router_data = router_data.clone();+ let connector_name = router_data.connector.clone();+ let merchant_id = router_data.merchant_id.clone();+ let payment_method = router_data.payment_method;+ let payment_method_type = router_data.payment_method_type;+ tokio::spawn(+ async move {+ let shadow_result =+ F::get_dispute_gateway(ExecutionPath::ShadowUnifiedConnectorService)+ .execute(+ &shadow_state,+ connector_integration,+ &shadow_router_data,+ context,+ )+ .await;+ if let Err(error) = &shadow_result {+ logger::warn!(+ ?error,+ execution_mode = "shadow",+ primary_impact = false,+ "UCS dispute shadow execution failed"+ );+ }+ if let Some(config) = shadow_state.get_comparison_service_config() {+ let comparison_data = helpers::ComparisonData {+ hyperswitch_data: Secret::new(direct_for_compare),+ unified_connector_service_data: Secret::new(dispute_comparison_value(+ &shadow_result,+ )),+ };+ if let Err(error) = helpers::send_comparison_data(+ &shadow_state,+ comparison_data,+ config,+ connector_name,+ api_client::get_flow_name::<F>().ok(),+ shadow_state.get_request_id_str(),+ Some(&merchant_id),+ Some(payment_method),+ payment_method_type,+ )+ .await+ {+ logger::warn!(?error, "Failed to send dispute shadow comparison");+ }+ }+ }+ .instrument(tracing::Span::current()),+ );+ direct_result+ }+ }+}+/// Converts a `Report<UnifiedConnectorServiceError>` into a `Report<ConnectorError>`/// using the `ErrorSwitch` trait for consistent, exhaustive mapping.///diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rsindex d732db3607..a54f925fc4 100644--- a/crates/router/src/core/disputes.rs+++ b/crates/router/src/core/disputes.rs@@ -7,6 +7,8 @@ use common_utils::ext_traits::{Encode, ValueExt};use error_stack::ResultExt;use router_env::{instrument, logger, tracing::Instrument};use strum::IntoEnumIterator;+#[cfg(feature = "v1")]+pub mod gateway;pub mod transformers;use common_enums;@@ -17,7 +19,7 @@ use super::{metrics,};use crate::{- core::{files, payments, utils as core_utils, webhooks},+ core::{files, payments, unified_connector_service, utils as core_utils, webhooks},routes::{app::StorageInterface, metrics::TASKS_ADDED_COUNT, SessionState},services,types::{@@ -486,25 +488,43 @@ pub async fn accept_dispute(AcceptDisputeRequestData,AcceptDisputeResponse,> = connector_data.connector.get_connector_integration();- let router_data = core_utils::construct_accept_dispute_router_data(+ let (router_data, merchant_connector_account) =+ core_utils::construct_accept_dispute_router_data(+ &state,+ &payment_intent,+ &payment_attempt,+ &processor,+ &dispute,+ )+ .await?;+ let (execution_path, updated_state, rollout_result) =+ unified_connector_service::should_call_unified_connector_service(+ &state,+ &processor,+ &router_data,+ None,+ payments::CallConnectorAction::Trigger,+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;+ let response = gateway::execute_dispute_gateway(&state,- &payment_intent,- &payment_attempt,+ &updated_state,&processor,- &dispute,- )- .await?;- let response = services::execute_connector_processing_step(- &state,+ router_data,connector_integration,- &router_data,- payments::CallConnectorAction::Trigger,- None,- None,+ gateway::DisputeGatewayContext {+ execution_path,+ rollout_result,+ merchant_connector_account,+ connector_transaction_id: payment_attempt+ .get_connector_payment_id()+ .map(ToString::to_string),+ },).await- .to_dispute_failed_response()- .attach_printable("Failed while calling accept dispute connector api")?;+ .attach_printable("Failed while executing accept dispute gateway")?;let accept_dispute_response =response.response@@ -617,26 +637,45 @@ pub async fn submit_evidence(SubmitEvidenceRequestData,SubmitEvidenceResponse,> = connector_data.connector.get_connector_integration();- let router_data = core_utils::construct_submit_evidence_router_data(+ let (router_data, merchant_connector_account) =+ core_utils::construct_submit_evidence_router_data(+ &state,+ &payment_intent,+ &payment_attempt,+ &processor,+ &dispute,+ submit_evidence_request_data,+ )+ .await?;+ let connector_transaction_id = payment_attempt+ .get_connector_payment_id()+ .map(ToString::to_string);+ let (execution_path, updated_state, rollout_result) =+ unified_connector_service::should_call_unified_connector_service(+ &state,+ &processor,+ &router_data,+ None,+ payments::CallConnectorAction::Trigger,+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;+ let response = Box::pin(gateway::execute_dispute_gateway(&state,- &payment_intent,- &payment_attempt,+ &updated_state,&processor,- &dispute,- submit_evidence_request_data,- )- .await?;- let response = services::execute_connector_processing_step(- &state,+ router_data,connector_integration,- &router_data,- payments::CallConnectorAction::Trigger,- None,- None,- )+ gateway::DisputeGatewayContext {+ execution_path,+ rollout_result: rollout_result.clone(),+ merchant_connector_account: merchant_connector_account.clone(),+ connector_transaction_id: connector_transaction_id.clone(),+ },+ )).await- .to_dispute_failed_response()- .attach_printable("Failed while calling submit evidence connector api")?;+ .attach_printable("Failed while executing submit evidence gateway")?;let submit_evidence_response =response.response@@ -665,17 +704,23 @@ pub async fn submit_evidence(&dispute,).await?;- let defend_response = services::execute_connector_processing_step(+ // Submit evidence and defend form one connector operation for Adyen.+ // Keep both calls on the same execution path.+ let defend_response = Box::pin(gateway::execute_dispute_gateway(&state,+ &updated_state,+ &processor,+ defend_dispute_router_data,connector_integration_defend_dispute,- &defend_dispute_router_data,- payments::CallConnectorAction::Trigger,- None,- None,- )+ gateway::DisputeGatewayContext {+ execution_path,+ rollout_result,+ merchant_connector_account,+ connector_transaction_id,+ },+ )).await- .to_dispute_failed_response()- .attach_printable("Failed while calling defend dispute connector api")?;+ .attach_printable("Failed while executing defend dispute gateway")?;let defend_dispute_response = defend_response.response.map_err(|err| {errors::ApiErrorResponse::ExternalConnectorError {code: err.code,diff --git a/crates/router/src/core/disputes/gateway.rs b/crates/router/src/core/disputes/gateway.rsnew file mode 100644index 0000000000..d966fd9e1a--- /dev/null+++ b/crates/router/src/core/disputes/gateway.rs@@ -0,0 +1,126 @@+//! Gateway execution for dispute actions.++pub mod accept_gateway;+pub mod defend_gateway;+pub mod evidence_gateway;++use std::fmt::Debug;++use async_trait::async_trait;+use common_enums::ExecutionPath;+use hyperswitch_domain_models::router_data_v2::flow_common_types::DisputesFlowData;+use hyperswitch_interfaces::{+ api::gateway as interface_gateway, connector_integration_interface::RouterDataConversion,+};++use crate::{+ core::{errors::ConnectorErrorExt, payments::helpers, unified_connector_service},+ errors::RouterResult,+ routes::SessionState,+ services,+ types::{self, domain},+};++#[derive(Clone)]+pub struct DisputeGatewayContext {+ pub execution_path: ExecutionPath,+ pub rollout_result: helpers::RolloutExecutionResult,+ pub merchant_connector_account: helpers::MerchantConnectorAccountType,+ pub connector_transaction_id: Option<String>,+}++#[derive(Clone)]+pub struct DisputeGatewayExecutionContext {+ processor: domain::Processor,+ dispute: DisputeGatewayContext,+}++impl interface_gateway::GatewayContext for DisputeGatewayExecutionContext {+ fn execution_path(&self) -> ExecutionPath {+ self.dispute.execution_path+ }++ fn execution_mode(&self) -> common_enums::ExecutionMode {+ self.dispute.execution_path.get_execution_mode()+ }+}++impl DisputeGatewayContext {+ fn rollout_settings(&self) -> unified_connector_service::kill_switch::RolloutSettings {+ let mut settings = self.rollout_result.rollout_settings();+ settings.execution_mode = self.execution_path.get_execution_mode();+ settings+ }+}++pub struct DirectDisputeGateway;++#[async_trait]+impl<Flow, Req, Resp>+ interface_gateway::DisputeGateway<+ SessionState,+ DisputesFlowData,+ Flow,+ Req,+ Resp,+ DisputeGatewayExecutionContext,+ > for DirectDisputeGateway+where+ Flow: Clone + Debug + Send + Sync + 'static,+ Req: Debug + Clone + Send + Sync + 'static,+ Resp: Debug + Clone + Send + Sync + 'static,+ DisputesFlowData: RouterDataConversion<Flow, Req, Resp>,+{+ async fn execute(+ self: Box<Self>,+ state: &SessionState,+ connector_integration: services::BoxedDisputeConnectorIntegrationInterface<Flow, Req, Resp>,+ router_data: &types::RouterData<Flow, Req, Resp>,+ _context: DisputeGatewayExecutionContext,+ ) -> RouterResult<types::RouterData<Flow, Req, Resp>> {+ services::execute_connector_processing_step(+ state,+ connector_integration,+ router_data,+ common_enums::CallConnectorAction::Trigger,+ None,+ None,+ )+ .await+ .to_dispute_failed_response()+ }+}++/// Run a dispute action through the shared gateway executor.+pub async fn execute_dispute_gateway<Flow, Req, Resp>(+ state: &SessionState,+ ucs_state: &SessionState,+ processor: &domain::Processor,+ router_data: types::RouterData<Flow, Req, Resp>,+ connector_integration: services::BoxedDisputeConnectorIntegrationInterface<Flow, Req, Resp>,+ context: DisputeGatewayContext,+) -> RouterResult<types::RouterData<Flow, Req, Resp>>+where+ Flow: interface_gateway::DisputeFlowGateway<+ SessionState,+ DisputesFlowData,+ Req,+ Resp,+ DisputeGatewayExecutionContext,+ >,+ Req: Debug + Clone + Send + Sync + 'static,+ Resp: Debug + Clone + Send + Sync + 'static,+ DisputesFlowData: RouterDataConversion<Flow, Req, Resp>,+{+ interface_gateway::execute_dispute_gateway(+ state,+ ucs_state,+ connector_integration,+ &router_data,+ DisputeGatewayExecutionContext {+ processor: processor.clone(),+ dispute: context,+ },+ )+ .await+}diff --git a/crates/router/src/core/disputes/gateway/accept_gateway.rs b/crates/router/src/core/disputes/gateway/accept_gateway.rsnew file mode 100644index 0000000000..5b80a1caeb--- /dev/null+++ b/crates/router/src/core/disputes/gateway/accept_gateway.rs@@ -0,0 +1,167 @@+use std::str::FromStr;++use async_trait::async_trait;+use common_enums::ExecutionPath;+use common_utils::{id_type, ucs_types};+use error_stack::ResultExt;+use external_services::grpc_client::LineageIds;+#[cfg(feature = "v2")]+use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountTypeDetails;+use hyperswitch_domain_models::{+ platform::Processor, router_data::RouterData,+ router_data_v2::flow_common_types::DisputesFlowData, router_flow_types::dispute,+ router_request_types::AcceptDisputeRequestData, router_response_types::AcceptDisputeResponse,+};+use hyperswitch_interfaces::api::gateway as interface_gateway;+use router_env::instrument;+use unified_connector_service_client::payments as payments_grpc;++use super::{DirectDisputeGateway, DisputeGatewayExecutionContext};+use crate::{+ core::{errors, payments::helpers::MerchantConnectorAccountType, unified_connector_service},+ errors::RouterResult,+ routes::SessionState,+ services,+ types::{self, transformers::ForeignTryFrom},+};++#[async_trait]+impl+ interface_gateway::DisputeGateway<+ SessionState,+ DisputesFlowData,+ Self,+ AcceptDisputeRequestData,+ AcceptDisputeResponse,+ DisputeGatewayExecutionContext,+ > for dispute::Accept+{+ async fn execute(+ self: Box<Self>,+ state: &SessionState,+ _connector_integration: services::BoxedDisputeConnectorIntegrationInterface<+ Self,+ AcceptDisputeRequestData,+ AcceptDisputeResponse,+ >,+ router_data: &types::AcceptDisputeRouterData,+ context: DisputeGatewayExecutionContext,+ ) -> RouterResult<types::AcceptDisputeRouterData> {+ let rollout_settings = context.dispute.rollout_settings();+ call_unified_connector_service_for_dispute_accept(+ state,+ &context.processor,+ router_data.clone(),+ context.dispute.connector_transaction_id,+ rollout_settings,+ context.dispute.merchant_connector_account,+ )+ .await+ .map_err(|error| error.attach_printable("Failed while calling accept via UCS"))+ }+}++impl+ interface_gateway::DisputeFlowGateway<+ SessionState,+ DisputesFlowData,+ AcceptDisputeRequestData,+ AcceptDisputeResponse,+ DisputeGatewayExecutionContext,+ > for dispute::Accept+{+ fn get_dispute_gateway(+ execution_path: ExecutionPath,+ ) -> Box<+ dyn interface_gateway::DisputeGateway<+ SessionState,+ DisputesFlowData,+ Self,+ AcceptDisputeRequestData,+ AcceptDisputeResponse,+ DisputeGatewayExecutionContext,+ >,+ > {+ match execution_path {+ ExecutionPath::Direct => Box::new(DirectDisputeGateway),+ ExecutionPath::UnifiedConnectorService+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),+ }+ }+}++/// Execute a dispute accept using DisputeService.Accept.+#[instrument(skip_all)]+async fn call_unified_connector_service_for_dispute_accept(+ state: &SessionState,+ processor: &Processor,+ router_data: RouterData<dispute::Accept, AcceptDisputeRequestData, AcceptDisputeResponse>,+ connector_transaction_id: Option<String>,+ rollout_settings: unified_connector_service::kill_switch::RolloutSettings,+ #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,+ #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,+) -> RouterResult<RouterData<dispute::Accept, AcceptDisputeRequestData, AcceptDisputeResponse>> {+ let ucs_client = unified_connector_service::get_ucs_client(state)?;+ let connector_auth_metadata =+ unified_connector_service::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor.get_account().get_id(),+ router_data.connector.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS auth metadata for dispute accept")?;+ let grpc_request = payments_grpc::DisputeServiceAcceptRequest::foreign_try_from((+ &router_data,+ connector_transaction_id,+ ))+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to transform router data to UCS dispute accept request")?;++ let merchant_id = processor.get_account().get_id().clone();+ let profile_id = id_type::ProfileId::from_str(merchant_id.get_string_repr())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert merchant_id to profile_id for UCS dispute accept")?;+ let lineage_ids = LineageIds::new(merchant_id, profile_id);+ let merchant_reference_id =+ id_type::PaymentReferenceId::from_str(router_data.payment_id.as_str())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert payment_id to UCS reference id")+ .map(ucs_types::UcsReferenceId::Payment)+ .map(Some)?;+ // UcsResourceId has no dispute variant; the dispute is identified by the request body.+ let grpc_header_builder = state+ .get_grpc_headers_ucs(rollout_settings.execution_mode)+ .payment_method(Some(router_data.payment_method))+ .payment_method_type(router_data.payment_method_type)+ .lineage_ids(lineage_ids)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .resource_id(None);++ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(+ router_data,+ state,+ grpc_request,+ grpc_header_builder,+ rollout_settings.clone(),+ |mut router_data, grpc_request, grpc_headers| async move {+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.+ let grpc_response = ucs_client+ .dispute_accept(grpc_request, connector_auth_metadata, grpc_headers)+ .await+ .attach_printable("UCS dispute accept execution failed")?+ .into_inner();+ let (router_data_response, status_code) =+ unified_connector_service::handle_unified_connector_service_response_for_dispute_accept(grpc_response.clone())+ .attach_printable("Failed to transform UCS dispute accept response")?;++ router_data.connector_http_status_code = Some(status_code);+ router_data.response = router_data_response;++ Ok((router_data, (), grpc_response))+ },+ ))+ .await+ .map(|(router_data, _flow_response)| router_data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+}diff --git a/crates/router/src/core/disputes/gateway/defend_gateway.rs b/crates/router/src/core/disputes/gateway/defend_gateway.rsnew file mode 100644index 0000000000..9a5b330d16--- /dev/null+++ b/crates/router/src/core/disputes/gateway/defend_gateway.rs@@ -0,0 +1,167 @@+use std::str::FromStr;++use async_trait::async_trait;+use common_enums::ExecutionPath;+use common_utils::{id_type, ucs_types};+use error_stack::ResultExt;+use external_services::grpc_client::LineageIds;+#[cfg(feature = "v2")]+use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountTypeDetails;+use hyperswitch_domain_models::{+ platform::Processor, router_data::RouterData,+ router_data_v2::flow_common_types::DisputesFlowData, router_flow_types::dispute,+ router_request_types::DefendDisputeRequestData, router_response_types::DefendDisputeResponse,+};+use hyperswitch_interfaces::api::gateway as interface_gateway;+use router_env::instrument;+use unified_connector_service_client::payments as payments_grpc;++use super::{DirectDisputeGateway, DisputeGatewayExecutionContext};+use crate::{+ core::{errors, payments::helpers::MerchantConnectorAccountType, unified_connector_service},+ errors::RouterResult,+ routes::SessionState,+ services,+ types::{self, transformers::ForeignTryFrom},+};++#[async_trait]+impl+ interface_gateway::DisputeGateway<+ SessionState,+ DisputesFlowData,+ Self,+ DefendDisputeRequestData,+ DefendDisputeResponse,+ DisputeGatewayExecutionContext,+ > for dispute::Defend+{+ async fn execute(+ self: Box<Self>,+ state: &SessionState,+ _connector_integration: services::BoxedDisputeConnectorIntegrationInterface<+ Self,+ DefendDisputeRequestData,+ DefendDisputeResponse,+ >,+ router_data: &types::DefendDisputeRouterData,+ context: DisputeGatewayExecutionContext,+ ) -> RouterResult<types::DefendDisputeRouterData> {+ let rollout_settings = context.dispute.rollout_settings();+ call_unified_connector_service_for_dispute_defend(+ state,+ &context.processor,+ router_data.clone(),+ context.dispute.connector_transaction_id,+ rollout_settings,+ context.dispute.merchant_connector_account,+ )+ .await+ .map_err(|error| error.attach_printable("Failed while calling defend via UCS"))+ }+}++impl+ interface_gateway::DisputeFlowGateway<+ SessionState,+ DisputesFlowData,+ DefendDisputeRequestData,+ DefendDisputeResponse,+ DisputeGatewayExecutionContext,+ > for dispute::Defend+{+ fn get_dispute_gateway(+ execution_path: ExecutionPath,+ ) -> Box<+ dyn interface_gateway::DisputeGateway<+ SessionState,+ DisputesFlowData,+ Self,+ DefendDisputeRequestData,+ DefendDisputeResponse,+ DisputeGatewayExecutionContext,+ >,+ > {+ match execution_path {+ ExecutionPath::Direct => Box::new(DirectDisputeGateway),+ ExecutionPath::UnifiedConnectorService+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),+ }+ }+}++/// Execute a dispute defend using DisputeService.Defend.+#[instrument(skip_all)]+async fn call_unified_connector_service_for_dispute_defend(+ state: &SessionState,+ processor: &Processor,+ router_data: RouterData<dispute::Defend, DefendDisputeRequestData, DefendDisputeResponse>,+ connector_transaction_id: Option<String>,+ rollout_settings: unified_connector_service::kill_switch::RolloutSettings,+ #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,+ #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,+) -> RouterResult<RouterData<dispute::Defend, DefendDisputeRequestData, DefendDisputeResponse>> {+ let ucs_client = unified_connector_service::get_ucs_client(state)?;+ let connector_auth_metadata =+ unified_connector_service::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor.get_account().get_id(),+ router_data.connector.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS auth metadata for dispute defend")?;+ let grpc_request = payments_grpc::DisputeServiceDefendRequest::foreign_try_from((+ &router_data,+ connector_transaction_id,+ ))+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to transform router data to UCS dispute defend request")?;++ let merchant_id = processor.get_account().get_id().clone();+ let profile_id = id_type::ProfileId::from_str(merchant_id.get_string_repr())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert merchant_id to profile_id for UCS dispute defend")?;+ let lineage_ids = LineageIds::new(merchant_id, profile_id);+ let merchant_reference_id =+ id_type::PaymentReferenceId::from_str(router_data.payment_id.as_str())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert payment_id to UCS reference id")+ .map(ucs_types::UcsReferenceId::Payment)+ .map(Some)?;+ // UcsResourceId has no dispute variant; the dispute is identified by the request body.+ let grpc_header_builder = state+ .get_grpc_headers_ucs(rollout_settings.execution_mode)+ .payment_method(Some(router_data.payment_method))+ .payment_method_type(router_data.payment_method_type)+ .lineage_ids(lineage_ids)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .resource_id(None);++ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(+ router_data,+ state,+ grpc_request,+ grpc_header_builder,+ rollout_settings.clone(),+ |mut router_data, grpc_request, grpc_headers| async move {+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.+ let grpc_response = ucs_client+ .dispute_defend(grpc_request, connector_auth_metadata, grpc_headers)+ .await+ .attach_printable("UCS dispute defend execution failed")?+ .into_inner();+ let (router_data_response, status_code) =+ unified_connector_service::handle_unified_connector_service_response_for_dispute_defend(grpc_response.clone())+ .attach_printable("Failed to transform UCS dispute defend response")?;++ router_data.connector_http_status_code = Some(status_code);+ router_data.response = router_data_response;++ Ok((router_data, (), grpc_response))+ },+ ))+ .await+ .map(|(router_data, _flow_response)| router_data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+}diff --git a/crates/router/src/core/disputes/gateway/evidence_gateway.rs b/crates/router/src/core/disputes/gateway/evidence_gateway.rsnew file mode 100644index 0000000000..867c2e4db1--- /dev/null+++ b/crates/router/src/core/disputes/gateway/evidence_gateway.rs@@ -0,0 +1,172 @@+use std::str::FromStr;++use async_trait::async_trait;+use common_enums::ExecutionPath;+use common_utils::{id_type, ucs_types};+use error_stack::ResultExt;+use external_services::grpc_client::LineageIds;+#[cfg(feature = "v2")]+use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountTypeDetails;+use hyperswitch_domain_models::{+ platform::Processor, router_data::RouterData,+ router_data_v2::flow_common_types::DisputesFlowData, router_flow_types::dispute,+ router_request_types::SubmitEvidenceRequestData, router_response_types::SubmitEvidenceResponse,+};+use hyperswitch_interfaces::api::gateway as interface_gateway;+use router_env::instrument;+use unified_connector_service_client::payments as payments_grpc;++use super::{DirectDisputeGateway, DisputeGatewayExecutionContext};+use crate::{+ core::{errors, payments::helpers::MerchantConnectorAccountType, unified_connector_service},+ errors::RouterResult,+ routes::SessionState,+ services,+ types::{self, transformers::ForeignTryFrom},+};++#[async_trait]+impl+ interface_gateway::DisputeGateway<+ SessionState,+ DisputesFlowData,+ Self,+ SubmitEvidenceRequestData,+ SubmitEvidenceResponse,+ DisputeGatewayExecutionContext,+ > for dispute::Evidence+{+ async fn execute(+ self: Box<Self>,+ state: &SessionState,+ _connector_integration: services::BoxedDisputeConnectorIntegrationInterface<+ Self,+ SubmitEvidenceRequestData,+ SubmitEvidenceResponse,+ >,+ router_data: &types::SubmitEvidenceRouterData,+ context: DisputeGatewayExecutionContext,+ ) -> RouterResult<types::SubmitEvidenceRouterData> {+ let rollout_settings = context.dispute.rollout_settings();+ call_unified_connector_service_for_dispute_submit_evidence(+ state,+ &context.processor,+ router_data.clone(),+ context.dispute.connector_transaction_id,+ rollout_settings,+ context.dispute.merchant_connector_account,+ )+ .await+ .map_err(|error| error.attach_printable("Failed while calling submit evidence via UCS"))+ }+}++impl+ interface_gateway::DisputeFlowGateway<+ SessionState,+ DisputesFlowData,+ SubmitEvidenceRequestData,+ SubmitEvidenceResponse,+ DisputeGatewayExecutionContext,+ > for dispute::Evidence+{+ fn get_dispute_gateway(+ execution_path: ExecutionPath,+ ) -> Box<+ dyn interface_gateway::DisputeGateway<+ SessionState,+ DisputesFlowData,+ Self,+ SubmitEvidenceRequestData,+ SubmitEvidenceResponse,+ DisputeGatewayExecutionContext,+ >,+ > {+ match execution_path {+ ExecutionPath::Direct => Box::new(DirectDisputeGateway),+ ExecutionPath::UnifiedConnectorService+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),+ }+ }+}++/// Execute a dispute submit evidence using DisputeService.SubmitEvidence.+#[instrument(skip_all)]+async fn call_unified_connector_service_for_dispute_submit_evidence(+ state: &SessionState,+ processor: &Processor,+ router_data: RouterData<dispute::Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>,+ connector_transaction_id: Option<String>,+ rollout_settings: unified_connector_service::kill_switch::RolloutSettings,+ #[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,+ #[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,+) -> RouterResult<RouterData<dispute::Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>>+{+ let ucs_client = unified_connector_service::get_ucs_client(state)?;+ let connector_auth_metadata =+ unified_connector_service::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ processor.get_account().get_id(),+ router_data.connector.clone(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to build UCS auth metadata for dispute submit evidence")?;+ let grpc_request = payments_grpc::DisputeServiceSubmitEvidenceRequest::foreign_try_from((+ &router_data,+ connector_transaction_id,+ ))+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to transform router data to UCS dispute submit evidence request")?;++ let merchant_id = processor.get_account().get_id().clone();+ let profile_id = id_type::ProfileId::from_str(merchant_id.get_string_repr())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to convert merchant_id to profile_id for UCS dispute submit evidence",+ )?;+ let lineage_ids = LineageIds::new(merchant_id, profile_id);+ let merchant_reference_id =+ id_type::PaymentReferenceId::from_str(router_data.payment_id.as_str())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to convert payment_id to UCS reference id")+ .map(ucs_types::UcsReferenceId::Payment)+ .map(Some)?;+ // UcsResourceId has no dispute variant; the dispute is identified by the request body.+ let grpc_header_builder = state+ .get_grpc_headers_ucs(rollout_settings.execution_mode)+ .payment_method(Some(router_data.payment_method))+ .payment_method_type(router_data.payment_method_type)+ .lineage_ids(lineage_ids)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .resource_id(None);++ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(+ router_data,+ state,+ grpc_request,+ grpc_header_builder,+ rollout_settings.clone(),+ |mut router_data, grpc_request, grpc_headers| async move {+ // UCS connector errors are handled by the wrapper — see `ucs_logging_wrapper_granular`.+ let grpc_response = ucs_client+ .dispute_submit_evidence(grpc_request, connector_auth_metadata, grpc_headers)+ .await+ .attach_printable("UCS dispute submit evidence execution failed")?+ .into_inner();+ let (router_data_response, status_code) =+ unified_connector_service::handle_unified_connector_service_response_for_dispute_submit_evidence(+ grpc_response.clone(),+ )+ .attach_printable("Failed to transform UCS dispute submit evidence response")?;++ router_data.connector_http_status_code = Some(status_code);+ router_data.response = router_data_response;++ Ok((router_data, (), grpc_response))+ },+ ))+ .await+ .map(|(router_data, _flow_response)| router_data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+}diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex cb97a0bc83..a5d4b61f09 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -37,8 +37,8 @@ use hyperswitch_domain_models::{router_flow_types::refunds,router_request_types::{RefundsData, ResponseId},router_response_types::{- fraud_check::FraudCheckResponseData, PaymentsResponseData, PayoutsResponseData,- RefundsResponseData,+ fraud_check::FraudCheckResponseData, AcceptDisputeResponse, DefendDisputeResponse,+ PaymentsResponseData, PayoutsResponseData, RefundsResponseData, SubmitEvidenceResponse,},};use hyperswitch_interfaces::{consts as interface_consts, helpers as interface_helpers};@@ -1649,8 +1649,10 @@ pub fn build_merchant_rollout_scope(let payment_method_str = payment_method.to_string();match flow_name {- // Refund keys carry no payment method.- "Execute" | "RSync" => format!("{merchant_id}_{connector_name}_{flow_name}"),+ // Refund and dispute keys carry no payment method.+ "Execute" | "RSync" | "Accept" | "Evidence" | "Defend" => {+ format!("{merchant_id}_{connector_name}_{flow_name}")+ }_ => match payment_method {// These payment methods are discriminated further by payment method type.@@ -1699,75 +1701,52 @@ fn build_rollout_keys_and_context(payment_method: common_enums::PaymentMethod,payment_method_type: Option<PaymentMethodType>,) -> (Vec<String>, superposition::ConfigContext) {- let prefix = consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX;- let is_refund_flow = matches!(flow_name, "Execute" | "RSync");+ let scope = build_merchant_rollout_scope(+ merchant_id,+ connector_name,+ flow_name,+ payment_method,+ payment_method_type,+ );+ let keys = build_rollout_keys_for_scope(org_id, merchant_id, &scope);- // Build base context (common for all flows)let mut context = superposition::ConfigContext::new().with("organization_id", org_id).with("processor_merchant_id", merchant_id).with("connector", connector_name).with("flow_name", flow_name);- let (merchant_connector_key, org_merchant_connector_key) = if is_refund_flow {- // Refund flows: ucs_rollout_config_<merchant_id>_<connector>_<flow>- (- format!("{prefix}_{merchant_id}_{connector_name}_{flow_name}"),- format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{flow_name}"),- )- } else {- let payment_method_str = payment_method.to_string();- match payment_method {+ // Refund and dispute scopes have no payment-method dimension.+ if !matches!(+ flow_name,+ "Execute" | "RSync" | "Accept" | "Evidence" | "Defend"+ ) {+ context = context.with("payment_method", &payment_method.to_string());+ if matches!(+ payment_method,common_enums::PaymentMethod::Wallet- | common_enums::PaymentMethod::BankRedirect- | common_enums::PaymentMethod::Voucher- | common_enums::PaymentMethod::PayLater => {- let payment_method_type_str = payment_method_type- .map(|pmt| pmt.to_string())- .unwrap_or_else(|| "unknown".to_string());-- // Add payment_method and payment_method_type to context- context = context- .with("payment_method", &payment_method_str)- .with("payment_method_type", &payment_method_type_str);-- (- format!("{prefix}_{merchant_id}_{connector_name}_{payment_method_str}_{payment_method_type_str}_{flow_name}"),- format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{payment_method_str}_{payment_method_type_str}_{flow_name}"),- )- }- common_enums::PaymentMethod::Card- | common_enums::PaymentMethod::CardRedirect- | common_enums::PaymentMethod::Upi- | common_enums::PaymentMethod::Crypto- | common_enums::PaymentMethod::Reward- | common_enums::PaymentMethod::BankDebit- | common_enums::PaymentMethod::RealTimePayment- | common_enums::PaymentMethod::BankTransfer- | common_enums::PaymentMethod::GiftCard- | common_enums::PaymentMethod::MobilePayment- | common_enums::PaymentMethod::NetworkToken- | common_enums::PaymentMethod::OpenBanking => {- // Add payment_method to context- context = context.with("payment_method", &payment_method_str);-- (- format!("{prefix}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),- format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),- )- }+ | common_enums::PaymentMethod::BankRedirect+ | common_enums::PaymentMethod::Voucher+ | common_enums::PaymentMethod::PayLater+ ) {+ let payment_method_type = payment_method_type+ .map(|pmt| pmt.to_string())+ .unwrap_or_else(|| "unknown".to_string());+ context = context.with("payment_method_type", &payment_method_type);}- };+ }- // Ascending precedence order (lowest first, highest last)- let keys = vec![+ (keys, context)+}++fn build_rollout_keys_for_scope(org_id: &str, merchant_id: &str, scope: &str) -> Vec<String> {+ let prefix = consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX;+ vec![format!("{prefix}_{org_id}"),format!("{prefix}_{org_id}_{merchant_id}"),- org_merchant_connector_key,- merchant_connector_key,- ];-- (keys, context)+ format!("{prefix}_{org_id}_{scope}"),+ format!("{prefix}_{scope}"),+ ]}/// Build rollout key for payouts — single key, org-level precedence not applied to payouts yet.@@ -3110,7 +3089,7 @@ pub fn build_unified_connector_service_payment_method_for_external_proxy(}/// Gets the UCS client from session state-fn get_ucs_client(+pub(crate) fn get_ucs_client(state: &SessionState,) -> RouterResult<&external_services::grpc_client::unified_connector_service::UnifiedConnectorServiceClient,@@ -3993,6 +3972,150 @@ pub fn handle_unified_connector_service_response_for_refund_void_post_refund())}+impl ForeignTryFrom<payments_grpc::DisputeStatus> for common_enums::DisputeStatus {+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(status: payments_grpc::DisputeStatus) -> Result<Self, Self::Error> {+ match status {+ payments_grpc::DisputeStatus::DisputeOpened => Ok(Self::DisputeOpened),+ payments_grpc::DisputeStatus::DisputeExpired => Ok(Self::DisputeExpired),+ payments_grpc::DisputeStatus::DisputeAccepted => Ok(Self::DisputeAccepted),+ payments_grpc::DisputeStatus::DisputeCancelled => Ok(Self::DisputeCancelled),+ payments_grpc::DisputeStatus::DisputeChallenged => Ok(Self::DisputeChallenged),+ payments_grpc::DisputeStatus::DisputeWon => Ok(Self::DisputeWon),+ payments_grpc::DisputeStatus::DisputeLost => Ok(Self::DisputeLost),+ payments_grpc::DisputeStatus::Unspecified => Err(error_stack::Report::new(+ UnifiedConnectorServiceError::ResponseDeserializationFailed,+ )+ .attach_printable("UCS dispute response carried DISPUTE_STATUS_UNSPECIFIED")),+ }+ }+}++/// Builds the router-data error for a UCS dispute response that carries an `ErrorInfo`.+fn build_dispute_error_response(+ error_info: &payments_grpc::ErrorInfo,+ status_code: u16,+) -> Result<ErrorResponse, error_stack::Report<UnifiedConnectorServiceError>> {+ let connector_details = error_info.connector_details.as_ref();+ Ok(ErrorResponse {+ code: connector_details+ .and_then(|details| details.code.clone())+ .ok_or(+ error_stack::Report::new(+ UnifiedConnectorServiceError::ResponseDeserializationFailed,+ )+ .attach_printable("Missing error code in UCS dispute response ErrorInfo"),+ )?,+ message: connector_details+ .and_then(|details| details.message.clone())+ .ok_or(+ error_stack::Report::new(+ UnifiedConnectorServiceError::ResponseDeserializationFailed,+ )+ .attach_printable("Missing error message in UCS dispute response ErrorInfo"),+ )?,+ reason: connector_details.and_then(|details| details.reason.clone()),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: None,+ network_advice_code: None,+ network_error_message: None,+ connector_metadata: None,+ })+}++/// Return type of the shared UCS dispute response handler.+type UnifiedConnectorServiceDisputeResult = CustomResult<+ (+ Result<(common_enums::DisputeStatus, Option<String>), ErrorResponse>,+ u16,+ ),+ UnifiedConnectorServiceError,+>;++/// Shared shape of the three dispute responses: (dispute_status, connector_status) or error.+fn handle_unified_connector_service_dispute_response(+ error: Option<&payments_grpc::ErrorInfo>,+ dispute_status: payments_grpc::DisputeStatus,+ connector_status_code: Option<String>,+ grpc_status_code: u32,+) -> UnifiedConnectorServiceDisputeResult {+ let status_code = transformers::convert_connector_service_status_code(grpc_status_code)?;+ let response = match error {+ Some(error_info) => Err(build_dispute_error_response(error_info, status_code)?),+ None => Ok((+ common_enums::DisputeStatus::foreign_try_from(dispute_status)?,+ connector_status_code,+ )),+ };+ Ok((response, status_code))+}++pub fn handle_unified_connector_service_response_for_dispute_accept(+ response: payments_grpc::DisputeServiceAcceptResponse,+) -> CustomResult<(Result<AcceptDisputeResponse, ErrorResponse>, u16), UnifiedConnectorServiceError>+{+ let dispute_status = response.dispute_status();+ let (router_data_response, status_code) = handle_unified_connector_service_dispute_response(+ response.error.as_ref(),+ dispute_status,+ response.connector_status_code,+ response.status_code,+ )?;+ Ok((+ router_data_response.map(|(dispute_status, connector_status)| AcceptDisputeResponse {+ dispute_status,+ connector_status,+ }),+ status_code,+ ))+}++pub fn handle_unified_connector_service_response_for_dispute_submit_evidence(+ response: payments_grpc::DisputeServiceSubmitEvidenceResponse,+) -> CustomResult<(Result<SubmitEvidenceResponse, ErrorResponse>, u16), UnifiedConnectorServiceError>+{+ let dispute_status = response.dispute_status();+ let (router_data_response, status_code) = handle_unified_connector_service_dispute_response(+ response.error.as_ref(),+ dispute_status,+ response.connector_status_code,+ response.status_code,+ )?;+ Ok((+ router_data_response.map(+ |(dispute_status, connector_status)| SubmitEvidenceResponse {+ dispute_status,+ connector_status,+ },+ ),+ status_code,+ ))+}++pub fn handle_unified_connector_service_response_for_dispute_defend(+ response: payments_grpc::DisputeServiceDefendResponse,+) -> CustomResult<(Result<DefendDisputeResponse, ErrorResponse>, u16), UnifiedConnectorServiceError>+{+ let dispute_status = response.dispute_status();+ let (router_data_response, status_code) = handle_unified_connector_service_dispute_response(+ response.error.as_ref(),+ dispute_status,+ response.connector_status_code,+ response.status_code,+ )?;+ Ok((+ router_data_response.map(|(dispute_status, connector_status)| DefendDisputeResponse {+ dispute_status,+ connector_status,+ }),+ status_code,+ ))+}+pub fn handle_unified_connector_service_response_for_payment_cancel(response: payments_grpc::PaymentServiceVoidResponse,prev_status: AttemptStatus,@@ -4317,6 +4440,29 @@ pub fn build_webhook_secrets_from_merchant_connector_account(}}+fn redact_dispute_evidence_for_logging(value: &mut serde_json::Value) {+ match value {+ serde_json::Value::Object(fields) => {+ for (key, field) in fields {+ if matches!(+ key.as_str(),+ "file_content" | "fileContent" | "text_content" | "textContent"+ ) {+ *field = serde_json::Value::String("[REDACTED]".to_string());+ } else {+ redact_dispute_evidence_for_logging(field);+ }+ }+ }+ serde_json::Value::Array(items) => {+ for item in items {+ redact_dispute_evidence_for_logging(item);+ }+ }+ _ => {}+ }+}+/// Emit the connector event for a Hyperswitch -> UCS gRPC call, tagged/// `destination = unified_connector_service` (same `connector_events` stream as a direct call).#[allow(clippy::too_many_arguments)]@@ -4414,8 +4560,9 @@ wherelet router_data_clone = router_data.clone();let grpc_header = grpc_header_builder.build();// Log the actual gRPC request with masking- let grpc_request_body = hyperswitch_masking::masked_serialize(&grpc_request)+ let mut grpc_request_body = hyperswitch_masking::masked_serialize(&grpc_request).unwrap_or_else(|_| serde_json::json!({"error": "failed_to_serialize_grpc_request"}));+ redact_dispute_evidence_for_logging(&mut grpc_request_body);// Update connector call count metrics for UCS operationscrate::routes::metrics::CONNECTOR_CALL_COUNT.add(@@ -4651,8 +4798,9 @@ wherelet payment_method_type = router_data.payment_method_type;let grpc_header = grpc_header_builder.build();// Log the actual gRPC request with masking- let grpc_request_body = hyperswitch_masking::masked_serialize(&grpc_request)+ let mut grpc_request_body = hyperswitch_masking::masked_serialize(&grpc_request).unwrap_or_else(|_| serde_json::json!({"error": "failed_to_serialize_grpc_request"}));+ redact_dispute_evidence_for_logging(&mut grpc_request_body);// Update connector call count metrics for UCS operationscrate::routes::metrics::CONNECTOR_CALL_COUNT.add(diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 6509e18b46..984a18e93d 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -12180,6 +12180,244 @@ impl}}+/// Parses an evidence date into unix seconds. Accepts unix seconds, an RFC 3339+/// timestamp or an ISO 8601 calendar date (taken as midnight UTC); anything else is+/// refused rather than dropped.+fn parse_dispute_evidence_date(+ value: Option<&String>,+ field_name: &'static str,+) -> Result<Option<i64>, error_stack::Report<UnifiedConnectorServiceError>> {+ value+ .map(|raw| {+ let raw = raw.trim();+ raw.parse::<i64>()+ .ok()+ .or_else(|| {+ time::OffsetDateTime::parse(raw, &time::format_description::well_known::Rfc3339)+ .ok()+ .map(|date_time| date_time.unix_timestamp())+ })+ .or_else(|| {+ time::Date::parse(raw, &time::format_description::well_known::Iso8601::DATE)+ .ok()+ .map(|date| date.midnight().assume_utc().unix_timestamp())+ })+ .ok_or(+ UnifiedConnectorServiceError::InvalidDataFormat {+ field_name: field_name.into(),+ }+ .into(),+ )+ })+ .transpose()+}++fn build_dispute_evidence_document(+ evidence_type: payments_grpc::EvidenceType,+ file_content: Option<&Vec<u8>>,+ file_mime_type: Option<&String>,+ provider_file_id: Option<&String>,+ text_content: Option<&String>,+) -> Option<payments_grpc::EvidenceDocument> {+ (file_content.is_some()+ || file_mime_type.is_some()+ || provider_file_id.is_some()+ || text_content.is_some())+ .then(|| payments_grpc::EvidenceDocument {+ evidence_type: evidence_type.into(),+ file_content: file_content.cloned(),+ file_mime_type: file_mime_type.cloned(),+ provider_file_id: provider_file_id.cloned(),+ text_content: text_content.cloned(),+ })+}++impl transformers::ForeignTryFrom<(&crate::types::AcceptDisputeRouterData, Option<String>)>+ for payments_grpc::DisputeServiceAcceptRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ (router_data, connector_transaction_id): (+ &crate::types::AcceptDisputeRouterData,+ Option<String>,+ ),+ ) -> Result<Self, Self::Error> {+ Ok(Self {+ merchant_dispute_id: Some(router_data.request.dispute_id.clone()),+ // UCS Accept does not use the transaction ID; proto3 default when absent.+ connector_transaction_id: connector_transaction_id.unwrap_or_default(),+ connector_dispute_id: router_data.request.connector_dispute_id.clone(),+ })+ }+}++impl transformers::ForeignTryFrom<(&crate::types::DefendDisputeRouterData, Option<String>)>+ for payments_grpc::DisputeServiceDefendRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ (router_data, connector_transaction_id): (+ &crate::types::DefendDisputeRouterData,+ Option<String>,+ ),+ ) -> Result<Self, Self::Error> {+ Ok(Self {+ merchant_dispute_id: Some(router_data.request.dispute_id.clone()),+ // UCS Defend does not use the transaction ID; proto3 default when absent.+ connector_transaction_id: connector_transaction_id.unwrap_or_default(),+ connector_dispute_id: router_data.request.connector_dispute_id.clone(),+ // DefendDisputeRequestData carries no reason code.+ reason_code: None,+ })+ }+}++impl transformers::ForeignTryFrom<(&crate::types::SubmitEvidenceRouterData, Option<String>)>+ for payments_grpc::DisputeServiceSubmitEvidenceRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ (router_data, connector_transaction_id): (+ &crate::types::SubmitEvidenceRouterData,+ Option<String>,+ ),+ ) -> Result<Self, Self::Error> {+ let request = &router_data.request;+ let evidence_documents = [+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::CancellationPolicy,+ request.cancellation_policy.as_ref(),+ request.cancellation_policy_file_type.as_ref(),+ request.cancellation_policy_provider_file_id.as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::CustomerCommunication,+ request.customer_communication.as_ref(),+ request.customer_communication_file_type.as_ref(),+ request.customer_communication_provider_file_id.as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::CustomerSignature,+ request.customer_signature.as_ref(),+ request.customer_signature_file_type.as_ref(),+ request.customer_signature_provider_file_id.as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::Receipt,+ request.receipt.as_ref(),+ request.receipt_file_type.as_ref(),+ request.receipt_provider_file_id.as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::RefundPolicy,+ request.refund_policy.as_ref(),+ request.refund_policy_file_type.as_ref(),+ request.refund_policy_provider_file_id.as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::ServiceDocumentation,+ request.service_documentation.as_ref(),+ request.service_documentation_file_type.as_ref(),+ request.service_documentation_provider_file_id.as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::ShippingDocumentation,+ request.shipping_documentation.as_ref(),+ request.shipping_documentation_file_type.as_ref(),+ request.shipping_documentation_provider_file_id.as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::InvoiceShowingDistinctTransactions,+ request.invoice_showing_distinct_transactions.as_ref(),+ request+ .invoice_showing_distinct_transactions_file_type+ .as_ref(),+ request+ .invoice_showing_distinct_transactions_provider_file_id+ .as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::RecurringTransactionAgreement,+ request.recurring_transaction_agreement.as_ref(),+ request.recurring_transaction_agreement_file_type.as_ref(),+ request+ .recurring_transaction_agreement_provider_file_id+ .as_ref(),+ None,+ ),+ build_dispute_evidence_document(+ payments_grpc::EvidenceType::UncategorizedFile,+ request.uncategorized_file.as_ref(),+ request.uncategorized_file_type.as_ref(),+ request.uncategorized_file_provider_file_id.as_ref(),+ request.uncategorized_text.as_ref(),+ ),+ ]+ .into_iter()+ .flatten()+ .collect();++ Ok(Self {+ merchant_dispute_id: Some(request.dispute_id.clone()),+ // proto field is optional and unused by UCS SubmitEvidenceData.+ connector_transaction_id,+ connector_dispute_id: request.connector_dispute_id.clone(),+ service_date: parse_dispute_evidence_date(+ request.service_date.as_ref(),+ "service_date",+ )?,+ shipping_date: parse_dispute_evidence_date(+ request.shipping_date.as_ref(),+ "shipping_date",+ )?,+ evidence_documents,+ access_activity_log: request.access_activity_log.clone(),+ billing_address: request.billing_address.as_ref().map(|address| {+ payments_grpc::Address {+ line1: Some(Secret::new(address.clone())),+ ..Default::default()+ }+ }),+ cancellation_policy_disclosure: request.cancellation_policy_disclosure.clone(),+ cancellation_rebuttal: request.cancellation_rebuttal.clone(),+ customer_email_address: request+ .customer_email_address+ .as_ref()+ .map(|email| Secret::new(email.peek().to_owned())),+ customer_name: request+ .customer_name+ .as_ref()+ .map(|name| Secret::new(name.clone())),+ customer_purchase_ip: request+ .customer_purchase_ip+ .as_ref()+ .map(|ip| Secret::new(ip.clone())),+ product_description: request.product_description.clone(),+ refund_policy_disclosure: request.refund_policy_disclosure.clone(),+ refund_refusal_explanation: request.refund_refusal_explanation.clone(),+ shipping_address: request.shipping_address.as_ref().map(|address| {+ payments_grpc::Address {+ line1: Some(Secret::new(address.clone())),+ ..Default::default()+ }+ }),+ shipping_carrier: request.shipping_carrier.clone(),+ shipping_tracking_number: request.shipping_tracking_number.clone(),+ })+ }+}+impl transformers::ForeignTryFrom<&PaymentsSurchargeRefundInitData>for payments_grpc::SurchargeServiceSurchargeRefundInitRequest{diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex db704d7773..81add56dc4 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -1224,7 +1224,10 @@ pub async fn construct_accept_dispute_router_data<'a>(payment_attempt: &storage::PaymentAttempt,processor: &domain::Processor,dispute: &storage::Dispute,-) -> RouterResult<types::AcceptDisputeRouterData> {+) -> RouterResult<(+ types::AcceptDisputeRouterData,+ helpers::MerchantConnectorAccountType,+)> {let profile_id = payment_intent.profile_id.as_ref()@@ -1330,7 +1333,7 @@ pub async fn construct_accept_dispute_router_data<'a>(connector_returned_payment_method_details: None,customer_date_of_birth: None,};- Ok(router_data)+ Ok((router_data, merchant_connector_account))}#[cfg(feature = "v1")]@@ -1342,7 +1345,10 @@ pub async fn construct_submit_evidence_router_data<'a>(processor: &domain::Processor,dispute: &storage::Dispute,submit_evidence_request_data: types::SubmitEvidenceRequestData,-) -> RouterResult<types::SubmitEvidenceRouterData> {+) -> RouterResult<(+ types::SubmitEvidenceRouterData,+ helpers::MerchantConnectorAccountType,+)> {let connector_id = &dispute.connector;let profile_id = payment_intent.profile_id@@ -1445,7 +1451,7 @@ pub async fn construct_submit_evidence_router_data<'a>(connector_returned_payment_method_details: None,customer_date_of_birth: None,};- Ok(router_data)+ Ok((router_data, merchant_connector_account))}#[cfg(feature = "v1")]diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rsindex 15011cdbbc..2755990eef 100644--- a/crates/router/src/routes/disputes.rs+++ b/crates/router/src/routes/disputes.rs@@ -506,12 +506,13 @@ pub async fn submit_dispute_evidence(json_payload.into_inner(),|state, auth: auth::AuthenticationData, req, _| {let profile_id = auth.profile.map(|profile| profile.get_id().clone());- disputes::submit_evidence(+ // Evidence may execute both submit and defend; keep the flow future off the worker stack.+ Box::pin(disputes::submit_evidence(state,auth.platform.get_processor().clone(),profile_id,req,- )+ ))},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {