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(core): route webhooks to UCS based on flow-level rollout config (#12705)
Vani Gupta6e35007cca52
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rsindex 62acb9658f..663f293112 100644--- a/crates/api_models/src/webhooks.rs+++ b/crates/api_models/src/webhooks.rs@@ -133,6 +133,7 @@ impl IncomingWebhookEvent {}}+#[derive(Clone, Debug, Deserialize, PartialEq, strum::EnumString, strum::Display)]pub enum WebhookFlow {Payment,#[cfg(feature = "payouts")]diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 045844a207..563158fb2c 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -69,7 +69,8 @@ use rand::Rng;use redis_interface::errors::RedisError;use router_env::{instrument, logger, tracing};use rust_decimal::Decimal;-use serde::{Deserialize, Serialize};+use serde::{de::DeserializeOwned, Deserialize, Serialize};+use serde_with::{serde_as, VecSkipError};use uuid::Uuid;use x509_parser::parse_x509_certificate;@@ -2503,6 +2504,16 @@ pub struct RolloutConfig {pub execution_mode: ExecutionMode,}+#[serde_as]+#[derive(Default, Debug, Clone, Deserialize)]+pub struct WebhookRolloutConfig {+ #[serde(flatten)]+ pub rollout_configs: RolloutConfig,+ #[serde_as(as = "VecSkipError<_>")]+ #[serde(default)]+ pub webhook_flows: Vec<api::WebhookFlow>,+}+impl Default for RolloutConfig {fn default() -> Self {Self {@@ -2534,6 +2545,12 @@ impl Default for RolloutExecutionResult {}}+#[derive(Debug, Clone, Default)]+pub struct WebhookRolloutExecutionResult {+ pub rollout_execution_result: RolloutExecutionResult,+ pub webhook_flows: Vec<api::WebhookFlow>,+}+/// Validates a proxy URL, filtering out invalid ones and logging warningsfn validate_proxy_url(url: Option<String>, url_type: &str) -> Option<String> {url.and_then(|url_str| {@@ -2626,24 +2643,39 @@ impl From<RolloutConfig> for RolloutExecutionResult {}}-pub async fn should_execute_based_on_rollout(+impl From<WebhookRolloutConfig> for WebhookRolloutExecutionResult {+ fn from(config: WebhookRolloutConfig) -> Self {+ let webhook_flows = config.webhook_flows;+ let rollout_execution_result = RolloutExecutionResult::from(config.rollout_configs);+ Self {+ rollout_execution_result,+ webhook_flows,+ }+ }+}++pub async fn should_execute_based_on_rollout<C, R>(state: &SessionState,config_key: &str,-) -> RouterResult<RolloutExecutionResult> {+) -> RouterResult<R>+where+ C: DeserializeOwned,+ R: From<C> + Default,+{let db = state.store.as_ref();match db.find_config_by_key(config_key).await {Ok(rollout_config) => {// Parse as JSON - log error if it fails but don't propagate- Ok(serde_json::from_str::<RolloutConfig>(&rollout_config.config)- .map(RolloutExecutionResult::from)+ Ok(serde_json::from_str::<C>(&rollout_config.config)+ .map(R::from).map_err(|err| {logger::error!(error = ?err,config = %rollout_config.config,"Failed to parse rollout config as JSON. Defaulting to not execute and setting should_execute to false.");- RolloutExecutionResult::default()+ R::default()}).unwrap_or_default())}@@ -2664,7 +2696,7 @@ pub async fn should_execute_based_on_rollout();}}- Ok(RolloutExecutionResult::default())+ Ok(R::default())}}}diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 0734ebde41..ea54093686 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -48,7 +48,7 @@ use crate::{helpers::{is_ucs_enabled, should_execute_based_on_rollout,should_execute_based_on_rollout_with_precedence, MerchantConnectorAccountType,- ProxyOverride,+ ProxyOverride, WebhookRolloutConfig, WebhookRolloutExecutionResult,},OperationSessionGetters, OperationSessionSetters,},@@ -703,8 +703,7 @@ pub async fn should_call_unified_connector_service_for_webhooks(state: &SessionState,processor: &Processor,connector_name: &str,- merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,-) -> RouterResult<ExecutionPath> {+) -> RouterResult<(ExecutionPath, Vec<api_models::webhooks::WebhookFlow>)> {// Extract context informationlet merchant_id = processor.get_account().get_id().get_string_repr();@@ -717,15 +716,11 @@ pub async fn should_call_unified_connector_service_for_webhooks(// Check UCS availability using idiomatic helperlet ucs_availability = check_ucs_availability(state).await;- let connector_key = merchant_connector_id- .map(|id| id.get_string_repr().to_owned())- .unwrap_or_else(|| connector_name.to_string());-let rollout_key = format!("{}_{}_{}_{}",consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,merchant_id,- connector_key,+ connector_name,flow_name);@@ -736,7 +731,11 @@ pub async fn should_call_unified_connector_service_for_webhooks(// For webhooks, there is no previous gateway system to consider (webhooks are stateless)let previous_gateway = None;- let rollout_result = should_execute_based_on_rollout(state, &rollout_key).await?;+ let rollout_result = should_execute_based_on_rollout::<+ WebhookRolloutConfig,+ WebhookRolloutExecutionResult,+ >(state, &rollout_key)+ .await?;// Use the same decision logic as payments, with no call_connector_action to considerlet (gateway_system, execution_path) = if ucs_availability == UcsAvailability::Disabled {@@ -747,7 +746,7 @@ pub async fn should_call_unified_connector_service_for_webhooks(decide_execution_path(connector_integration_type,previous_gateway,- rollout_result.execution_mode,+ rollout_result.rollout_execution_result.execution_mode,)?};@@ -757,10 +756,10 @@ pub async fn should_call_unified_connector_service_for_webhooks(execution_path,merchant_id,connector_name,- flow_name+ flow_name,);- Ok(execution_path)+ Ok((execution_path, rollout_result.webhook_flows))}pub fn build_unified_connector_service_payment_method(diff --git a/crates/router/src/core/webhooks/gateway.rs b/crates/router/src/core/webhooks/gateway.rsindex dca224cad9..b6ec46eb50 100644--- a/crates/router/src/core/webhooks/gateway.rs+++ b/crates/router/src/core/webhooks/gateway.rs@@ -115,6 +115,8 @@ pub struct WebhookGatewayContext {pub merchant_connector_account: Option<domain::MerchantConnectorAccount>,pub execution_path: ExecutionPath,pub execution_mode: ExecutionMode,+ pub ucs_reference: Option<payments_grpc::EventReference>,+ pub ucs_event_type: Option<IncomingWebhookEvent>,}#[async_trait]@@ -167,6 +169,83 @@ impl FilterDecision {}}+// Classifies the webhook via UCS `ParseEvent` before UCS/Direct routing.+// Returns `None` on any UCS error which causes downstream routing to use the Hyperswitch (Direct) gateway.+pub async fn get_webhook_event_details_from_ucs(+ state: &SessionState,+ platform: &domain::Platform,+ connector: ConnectorEnum,+ connector_name: &str,+ merchant_connector_account: Option<&domain::MerchantConnectorAccount>,+ request: &IncomingWebhookRequestDetails<'_>,+) -> (+ Option<payments_grpc::EventReference>,+ Option<IncomingWebhookEvent>,+) {+ let client = match state.grpc_client.unified_connector_service_client.as_ref() {+ Some(client) => client.clone(),+ None => return (None, None),+ };++ let ctx = WebhookGatewayContext {+ state: state.clone(),+ platform: platform.clone(),+ connector,+ connector_name: connector_name.to_string(),+ merchant_connector_account: merchant_connector_account.cloned(),+ execution_path: ExecutionPath::Direct,+ execution_mode: ExecutionMode::NotApplicable,+ ucs_reference: None,+ ucs_event_type: None,+ };++ let parse_request = match payments_grpc::EventServiceParseRequest::foreign_try_from(request)+ .inspect_err(|error| {+ logger::debug!(?error, "Failed to build UCS ParseEvent request");+ }) {+ Ok(parse_request) => parse_request,+ Err(_) => return (None, None),+ };++ let parse_auth = match build_ucs_auth_metadata(&ctx, None).inspect_err(|error| {+ logger::debug!(?error, "Failed to build UCS auth metadata");+ }) {+ Ok(parse_auth) => parse_auth,+ Err(_) => return (None, None),+ };++ let parse_headers = build_ucs_headers_builder(&ctx, None, ExecutionMode::NotApplicable);++ let parse_response = match unified_connector_service::ucs_webhook_logging_wrapper(+ state,+ connector_name.to_string(),+ "EventServiceParseEvent",+ parse_request,+ parse_headers,+ |request, headers| async move {+ client+ .incoming_webhook_parse_event(request, parse_auth, headers)+ .await+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)+ .attach_printable("UCS ParseEvent call failed during webhook probe")+ .map(|response| response.into_inner())+ },+ )+ .await+ .inspect_err(|error| {+ logger::debug!(?error, "UCS ParseEvent failed");+ }) {+ Ok(parse_response) => parse_response,+ Err(_) => return (None, None),+ };++ let event_type = parse_response+ .event_type+ .map(IncomingWebhookEvent::from_ucs_event_type);++ (parse_response.reference, event_type)+}+pub struct DirectIncomingWebhookGateway;#[async_trait]@@ -243,11 +322,18 @@ impl IncomingWebhookGateway for DirectIncomingWebhookGateway {.attach_printable("Failed to identify event type in incoming webhook body"));}};+ let mut mca = None;+ let ack_creds = match reference {+ Some(ref reference) => {+ mca = resolve_mca(ctx, reference).await.ok();+ mca.clone().map(|mca| mca.connector_account_details.clone())+ }+ None => ctx+ .merchant_connector_account+ .as_ref()+ .map(|m| m.connector_account_details.clone()),+ };- let ack_creds = ctx- .merchant_connector_account- .as_ref()- .map(|m| m.connector_account_details.clone());let ack_response = ctx.connector.get_webhook_api_response(&decoded_request, None, ack_creds)@@ -267,7 +353,12 @@ impl IncomingWebhookGateway for DirectIncomingWebhookGateway {"Could not find object reference id in incoming webhook body",)})?;- let mca = resolve_mca(ctx, &reference).await?;++ let mca = mca.ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to resolve merchant connector account details")+ })?;+let source_verified =verify_webhook_source_via_connector(ctx, &decoded_request, &mca).await?;let resource_object = ctx@@ -329,36 +420,12 @@ impl IncomingWebhookGateway for UcsIncomingWebhookGateway {let connector_name = ctx.connector_name.clone();let merchant_event_id = build_merchant_event_id(ctx);- let parse_request = payments_grpc::EventServiceParseRequest::foreign_try_from(request)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to build UCS EventServiceParseRequest")?;- let parse_auth = build_ucs_auth_metadata(ctx, None)?;- let parse_headers = build_ucs_headers_builder(ctx, None, ctx.execution_mode);- let parse_client = client.clone();- let parse_response = unified_connector_service::ucs_webhook_logging_wrapper(- &ctx.state,- connector_name.clone(),- "EventServiceParseEvent",- parse_request,- parse_headers,- |request, headers| async move {- parse_client- .incoming_webhook_parse_event(request, parse_auth, headers)- .await- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)- .attach_printable("UCS ParseEvent call failed")- .map(|response| response.into_inner())- },- )- .await?;-- let reference = match parse_response.reference.as_ref() {+ let reference = match ctx.ucs_reference.as_ref() {Some(r) => event_reference_to_object_ref(r)?,None => None,};- let event_type = parse_response- .event_type- .map(IncomingWebhookEvent::from_ucs_event_type)+ let event_type = ctx+ .ucs_event_type.unwrap_or(IncomingWebhookEvent::EventNotSupported);let outcome = match FilterDecision::evaluate(event_type, ctx).await {diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex a968517db9..4cbd2cc5ab 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -201,6 +201,17 @@ pub async fn network_token_incoming_webhooks_wrapper<W: types::OutgoingWebhookTyOk(application_response)}+fn confirm_path_for_flow(+ candidate_path: common_enums::ExecutionPath,+ flow: Option<api::WebhookFlow>,+ enabled_flows: &[api::WebhookFlow],+) -> common_enums::ExecutionPath {+ match flow {+ Some(f) if enabled_flows.contains(&f) => candidate_path,+ _ => common_enums::ExecutionPath::Direct,+ }+}+#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(@@ -272,20 +283,39 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(let connector_name = mca_data.connector_name.clone();let mca_ref = mca_data.merchant_connector_account.as_ref();- let execution_path =+ let (candidate_path, enabled_flows) =unified_connector_service::should_call_unified_connector_service_for_webhooks(&state,platform.get_processor(),&connector_name,- mca_ref.map(|mca| &mca.merchant_connector_id),).await?;logger::info!(connector = %connector_name,- ?execution_path,- "Selected webhook execution path"+ ?candidate_path,+ "Selected webhook execution path for event parsing");+ let (ucs_event_reference, ucs_event_type) = match candidate_path {+ common_enums::ExecutionPath::UnifiedConnectorService+ | common_enums::ExecutionPath::ShadowUnifiedConnectorService => {+ super::gateway::get_webhook_event_details_from_ucs(+ &state,+ &platform,+ connector.clone(),+ &connector_name,+ mca_ref,+ &request_details,+ )+ .await+ }+ _ => (None, None),+ };++ let flow = ucs_event_type.map(api::WebhookFlow::from);++ let execution_path = confirm_path_for_flow(candidate_path, flow, &enabled_flows);+let execution_mode = match execution_path {common_enums::ExecutionPath::UnifiedConnectorService => {common_enums::ExecutionMode::Primary@@ -295,6 +325,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(}common_enums::ExecutionPath::Direct => common_enums::ExecutionMode::NotApplicable,};+ logger::info!(?execution_path, "Selected webhook execution path");let ctx = super::gateway::WebhookGatewayContext {state: state.clone(),@@ -304,7 +335,10 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(merchant_connector_account: mca_ref.cloned(),execution_path,execution_mode,+ ucs_reference: ucs_event_reference,+ ucs_event_type,};+let outcome =super::gateway::execute_incoming_webhook_gateway(&ctx, &request_details).await;@@ -3009,6 +3043,8 @@ pub async fn process_uas_incoming_webhook<'a>(merchant_connector_account: None,execution_path: common_enums::ExecutionPath::Direct,execution_mode: common_enums::ExecutionMode::NotApplicable,+ ucs_reference: None,+ ucs_event_type: None,};// Reuse inbound request metadata, but parse using UAS response body.