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: add metrics in payments confirm (#13700)
Kashifd5c459305893
diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rsindex 9604cb6795..64961ce1a6 100644--- a/crates/common_utils/src/keymanager.rs+++ b/crates/common_utils/src/keymanager.rs@@ -8,7 +8,9 @@ use error_stack::ResultExt;use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};use hyperswitch_masking::{PeekInterface, StrongSecret};use once_cell::sync::OnceCell;-use router_env::{instrument, logger, tracing};+use router_env::{+ global_meter, histogram_metric_f64, instrument, logger, metric_attributes, tracing,+};use time::OffsetDateTime;#[cfg(feature = "ext_services_latency")]@@ -30,6 +32,25 @@ static DEFAULT_ENCRYPTION_VERSION: &str = "v1";#[cfg(any(feature = "km_forward_x_request_id", feature = "ext_services_latency"))]const X_REQUEST_ID: &str = "X-Request-Id";+global_meter!(KEY_MANAGER_METER, "COMMON_UTILS_KEY_MANAGER");+histogram_metric_f64!(+ ENCRYPTION_SERVICE_CALL_DURATION,+ KEY_MANAGER_METER,+ name: "encryption_service.call.duration",+ description: "Duration of completed encryption-service call attempts",+ unit: "s",+);++fn encryption_service_operation(endpoint: &str) -> &'static str {+ match endpoint {+ "data/encrypt" => "encrypt",+ "data/decrypt" => "decrypt",+ "key/create" => "key_create",+ "key/transfer" => "key_transfer",+ _ => "other",+ }+}+/// Get keymanager client constructed from the url and state#[instrument(skip_all)]#[allow(unused_mut)]@@ -88,17 +109,37 @@ wherelet method_str = method.to_string();let start_time = std::time::Instant::now();- let response = client+ let response_result = client.request(method, url).json(&ConvertRaw::convert_raw(request_body)?).headers(headers).send()- .await- .change_context(errors::KeyManagerClientError::RequestNotSent(+ .await;++ let elapsed = start_time.elapsed();+ if let Some(context) = &state.metrics_context {+ let outcome = response_result.as_ref().map_or("failure", |response| {+ if response.status().is_success() {+ "success"+ } else {+ "failure"+ }+ });+ ENCRYPTION_SERVICE_CALL_DURATION.record(+ elapsed.as_secs_f64(),+ metric_attributes!(+ ("operation", encryption_service_operation(endpoint)),+ ("merchant_mode", context.merchant_mode),+ ("outcome", outcome),+ ),+ );+ }++ let response =+ response_result.change_context(errors::KeyManagerClientError::RequestNotSent("Unable to send request to encryption service".to_string(),))?;- let elapsed = start_time.elapsed();let latency_ms = elapsed.as_millis();let created_at_timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos();#[cfg(feature = "ext_services_latency")]diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rsindex 4038f3455e..81d79e6839 100644--- a/crates/common_utils/src/types/keymanager.rs+++ b/crates/common_utils/src/types/keymanager.rs@@ -36,6 +36,11 @@ macro_rules! impl_get_tenant_for_request {};}+#[derive(Debug, Clone)]+pub struct KeyManagerMetricsContext {+ pub merchant_mode: &'static str,+}+#[derive(Debug, Clone)]pub struct KeyManagerState {pub tenant_id: id_type::TenantId,@@ -51,6 +56,7 @@ pub struct KeyManagerState {pub cert: Secret<String>,pub infra_values: Option<serde_json::Value>,pub use_legacy_key_store_decryption: bool,+ pub metrics_context: Option<KeyManagerMetricsContext>,}impl KeyManagerState {@@ -70,6 +76,7 @@ impl KeyManagerState {cert: Default::default(),infra_values: Default::default(),use_legacy_key_store_decryption: false,+ metrics_context: None,}}diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex ce0a5e7c10..ca32286e40 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -3420,9 +3420,21 @@ wherelet jwekey = state.conf.jwekey.get_inner();let response_type_name = type_name!(T);- let response = services::call_connector_api(state, request, flow_name, None)- .await- .change_context(errors::VaultError::ApiError)?;+ let start = std::time::Instant::now();+ let response_result = services::call_connector_api(state, request, flow_name, None).await;+ if let Some(context) = state.payment_metrics_context {+ let operation = match flow_name {+ router_consts::LOCKER_ADD_CARD_PATH => "store",+ router_consts::LOCKER_RETRIEVE_CARD_PATH => "retrieve",+ router_consts::LOCKER_DELETE_CARD_PATH => "delete",+ _ => "other",+ };+ let succeeded = response_result+ .as_ref()+ .is_ok_and(|response| response.is_ok());+ metrics::record_vault_call(start.elapsed(), operation, succeeded, context);+ }+ let response = response_result.change_context(errors::VaultError::ApiError)?;let is_locker_call_succeeded = response.is_ok();diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex 03081bcc8c..64d5cd3637 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -1404,7 +1404,8 @@ pub async fn call_modular_payment_method_update(&state.conf.trace_header.header_name,);- UpdatePaymentMethod::call(+ let start = std::time::Instant::now();+ let result = UpdatePaymentMethod::call(state,&client,UpdatePaymentMethodV1Request {@@ -1413,8 +1414,17 @@ pub async fn call_modular_payment_method_update(modular_service_prefix: state.conf.micro_services.payment_methods_prefix.0.clone(),},)- .await- .map_err(|err| {+ .await;+ if let Some(context) = state.payment_metrics_context {+ routes::metrics::record_microservice_call(+ &result,+ start.elapsed(),+ "payment_method",+ "update",+ context,+ );+ }+ result.map_err(|err| {logger::error!(error=?err, "modular payment method update failed");::payment_methods::errors::ModularPaymentMethodError::UpdateFailed})?;@@ -2046,14 +2056,24 @@ pub async fn retrieve_pm_modular_service_call();//Modular service call- let pm_response =- pm_client::RetrievePaymentMethod::call(state, &client, payment_method_fetch_req)- .await- .map_err(|err| {- logger::debug!("Error in retrieving payment method: {:?}", err);- errors::ApiErrorResponse::InternalServerError- })- .attach_printable("Failed to retrieve payment method from modular service")?;+ let start = std::time::Instant::now();+ let result =+ pm_client::RetrievePaymentMethod::call(state, &client, payment_method_fetch_req).await;+ if let Some(context) = state.payment_metrics_context {+ routes::metrics::record_microservice_call(+ &result,+ start.elapsed(),+ "payment_method",+ "retrieve",+ context,+ );+ }+ let pm_response = result+ .map_err(|err| {+ logger::debug!("Error in retrieving payment method: {:?}", err);+ errors::ApiErrorResponse::InternalServerError+ })+ .attach_printable("Failed to retrieve payment method from modular service")?;Ok(pm_response)}@@ -2291,14 +2311,24 @@ pub async fn create_pm_modular_service_call();//Modular service call- let pm_response =- pm_client::CreatePaymentMethod::call(state, &client, payment_method_create_req)- .await- .map_err(|err| {- logger::debug!("Error in creating payment method: {:?}", err);- errors::ApiErrorResponse::InternalServerError- })- .attach_printable("Failed to create payment method in modular service")?;+ let start = std::time::Instant::now();+ let result =+ pm_client::CreatePaymentMethod::call(state, &client, payment_method_create_req).await;+ if let Some(context) = state.payment_metrics_context {+ routes::metrics::record_microservice_call(+ &result,+ start.elapsed(),+ "payment_method",+ "create",+ context,+ );+ }+ let pm_response = result+ .map_err(|err| {+ logger::debug!("Error in creating payment method: {:?}", err);+ errors::ApiErrorResponse::InternalServerError+ })+ .attach_printable("Failed to create payment method in modular service")?;Ok(pm_response)}diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex 8772f918d6..00c7391867 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -62,7 +62,7 @@ use crate::{payments::PaymentData,},db::StorageInterface,- routes::SessionState,+ routes::{metrics::MerchantMode, SessionState},types::{self, api, domain,storage::{self, enums},@@ -97,6 +97,15 @@ pub async fn get_feature_config(platform: &domain::Platform,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,) -> FeatureConfig {+ if let Some(context) = state.payment_metrics_context {+ return FeatureConfig {+ is_payment_method_modular_allowed: matches!(+ context.merchant_mode,+ MerchantMode::Modular+ ),+ };+ }+let dimensions = dimensions.with_organization_id(platformdiff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 99fac11cb2..8a53ec0c12 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -77,7 +77,7 @@ use super::{apple_pay_certificates_migration, blocklist, payment_link, subscription, webhook_events,};#[cfg(any(feature = "olap", feature = "oltp"))]-use super::{configs::*, customers, payments};+use super::{configs::*, customers, metrics::PaymentMetricsContext, payments};#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))]use super::{mandates::*, refunds::*};#[cfg(feature = "olap")]@@ -149,6 +149,8 @@ pub struct SessionState {pub infra_components: Option<serde_json::Value>,pub enhancement: Option<HashMap<String, String>>,pub superposition_service: Arc<SuperpositionClient>,+ /// Bounded request context used to correlate v1 payment I/O metrics.+ pub payment_metrics_context: Option<PaymentMetricsContext>,}impl scheduler::SchedulerSessionState for SessionState {fn get_db(&self) -> Box<dyn SchedulerInterface> {@@ -592,6 +594,7 @@ impl AppState {ca: km_conf.ca.clone(),infra_values: Self::process_env_mappings(conf.infra_values.clone()),use_legacy_key_store_decryption: km_conf.use_legacy_key_store_decryption,+ metrics_context: None,};match storage_impl {StorageImpl::Postgresql | StorageImpl::PostgresqlTest => match event_handler {@@ -694,6 +697,7 @@ impl AppState {infra_components: self.infra_components.clone(),enhancement: self.enhancement.clone(),superposition_service: self.superposition_service.clone(),+ payment_metrics_context: None,})}diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex 30176e21fe..9505d44ecc 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -1,7 +1,9 @@pub mod bg_metrics_collector;pub mod request;-use router_env::{counter_metric, global_meter, histogram_metric_f64};+use std::time::Duration;++use router_env::{counter_metric, global_meter, histogram_metric_f64, metric_attributes};global_meter!(GLOBAL_METER, "ROUTER_API");@@ -12,6 +14,111 @@ counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV missescounter_metric!(REQUESTS_RECEIVED, GLOBAL_METER);histogram_metric_f64!(REQUEST_TIME, GLOBAL_METER);+histogram_metric_f64!(+ PAYMENT_OPERATION_DURATION,+ GLOBAL_METER,+ name: "payment.operation.duration",+ description: "Duration of completed payment domain operations",+ unit: "s",+);+histogram_metric_f64!(+ MICROSERVICE_CLIENT_CALL_DURATION,+ GLOBAL_METER,+ name: "microservice.client.call.duration",+ description: "Duration of completed internal microservice call attempts",+ unit: "s",+);+histogram_metric_f64!(+ VAULT_CALL_DURATION,+ GLOBAL_METER,+ name: "vault.call.duration",+ description: "Duration of completed legacy vault call attempts",+ unit: "s",+);++#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::IntoStaticStr)]+#[strum(serialize_all = "snake_case")]+pub enum MerchantMode {+ Modular,+ NonModular,+}++impl MerchantMode {+ pub const fn from_modular_enabled(enabled: bool) -> Self {+ if enabled {+ Self::Modular+ } else {+ Self::NonModular+ }+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub struct PaymentMetricsContext {+ pub merchant_mode: MerchantMode,+}++impl PaymentMetricsContext {+ pub const fn payments_confirm(merchant_mode: MerchantMode) -> Self {+ Self { merchant_mode }+ }+}++pub fn record_payment_confirm<T, E>(+ result: &Result<T, E>,+ duration: Duration,+ context: PaymentMetricsContext,+) {+ let outcome = if result.is_ok() { "success" } else { "failure" };+ let merchant_mode: &'static str = context.merchant_mode.into();+ let attributes = metric_attributes!(+ ("operation", "confirm"),+ ("merchant_mode", merchant_mode),+ ("outcome", outcome),+ );++ PAYMENT_OPERATION_DURATION.record(duration.as_secs_f64(), attributes);+}++pub fn record_microservice_call<T, E>(+ result: &Result<T, E>,+ duration: Duration,+ service: &'static str,+ operation: &'static str,+ context: PaymentMetricsContext,+) {+ let merchant_mode: &'static str = context.merchant_mode.into();+ MICROSERVICE_CLIENT_CALL_DURATION.record(+ duration.as_secs_f64(),+ metric_attributes!(+ ("service", service),+ ("operation", operation),+ ("merchant_mode", merchant_mode),+ (+ "outcome",+ if result.is_ok() { "success" } else { "failure" }+ ),+ ),+ );+}++pub fn record_vault_call(+ duration: Duration,+ operation: &'static str,+ succeeded: bool,+ context: PaymentMetricsContext,+) {+ let merchant_mode: &'static str = context.merchant_mode.into();+ VAULT_CALL_DURATION.record(+ duration.as_secs_f64(),+ metric_attributes!(+ ("operation", operation),+ ("merchant_mode", merchant_mode),+ ("outcome", if succeeded { "success" } else { "failure" }),+ ),+ );+}+// Operation Level Metricscounter_metric!(PAYMENT_OPS_COUNT, GLOBAL_METER);diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex a9f07b07bc..5c32573d4f 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -1,3 +1,14 @@+#[cfg(feature = "v1")]+use std::time::Instant;++#[cfg(feature = "v1")]+use common_utils::types::keymanager::KeyManagerState;++#[cfg(feature = "v1")]+use crate::{+ core::utils::get_feature_config,+ routes::metrics::{record_payment_confirm, MerchantMode, PaymentMetricsContext},+};use crate::{core::{api_locking::{self, GetLockingInput},@@ -126,17 +137,36 @@ pub async fn payments_create(state,&req,payload,- |state, auth: auth::AuthenticationData, req, req_state| {- authorize_verify_select::<_>(- payments::PaymentCreate,- state,- req_state,- auth.platform,- auth.profile.map(|profile| profile.get_id().clone()),- header_payload.clone(),- req,- api::AuthFlow::Client,- )+ |mut state, auth: auth::AuthenticationData, req, req_state| {+ let header_payload = header_payload.clone();+ async move {+ let metrics_start = req+ .confirm+ .is_some_and(|confirm| confirm)+ .then(Instant::now);+ let metrics_context = if metrics_start.is_some() {+ Some(set_payment_confirm_metrics_context(&mut state, &auth.platform).await)+ } else {+ None+ };+ let result = Box::pin(authorize_verify_select::<_>(+ payments::PaymentCreate,+ state,+ req_state,+ auth.platform,+ auth.profile.map(|profile| profile.get_id().clone()),+ header_payload,+ req,+ api::AuthFlow::Client,+ ))+ .await;++ if let (Some(start), Some(context)) = (metrics_start, metrics_context) {+ record_payment_confirm(&result, start.elapsed(), context);+ }++ result+ }},auth_type,locking_action,@@ -1148,22 +1178,33 @@ pub async fn payments_confirm(state,&req,payload,- |state, auth: auth::AuthenticationData, mut req, req_state| {- // If client_secret is provided via SDK authorization header, use it- if let Some(client_secret) = auth.client_secret {- req.client_secret = Some(client_secret);- }+ |mut state, auth: auth::AuthenticationData, mut req, req_state| {+ let header_payload = header_payload.clone();+ async move {+ let metrics_start = Instant::now();+ let metrics_context =+ set_payment_confirm_metrics_context(&mut state, &auth.platform).await;- authorize_verify_select::<_>(- payments::PaymentConfirm,- state,- req_state,- auth.platform,- auth.profile.map(|profile| profile.get_id().clone()),- header_payload.clone(),- req,- auth_flow,- )+ // If client_secret is provided via SDK authorization header, use it+ if let Some(client_secret) = auth.client_secret {+ req.client_secret = Some(client_secret);+ }++ let result = Box::pin(authorize_verify_select::<_>(+ payments::PaymentConfirm,+ state,+ req_state,+ auth.platform,+ auth.profile.map(|profile| profile.get_id().clone()),+ header_payload,+ req,+ auth_flow,+ ))+ .await;++ record_payment_confirm(&result, metrics_start.elapsed(), metrics_context);+ result+ }},&*auth_type,locking_action,@@ -2573,6 +2614,27 @@ pub async fn payments_reject(.await}+#[cfg(feature = "v1")]+async fn set_payment_confirm_metrics_context(+ state: &mut app::SessionState,+ platform: &domain::Platform,+) -> PaymentMetricsContext {+ let dimensions = dimension_state::Dimensions::new()+ .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());+ let feature_config = get_feature_config(state, platform, &dimensions).await;+ let context = PaymentMetricsContext::payments_confirm(MerchantMode::from_modular_enabled(+ feature_config.is_payment_method_modular_allowed,+ ));++ state.payment_metrics_context = Some(context);+ state+ .store+ .set_key_manager_state(KeyManagerState::from(&*state));++ context+}+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]async fn authorize_verify_select<Op>(diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rsindex 0fc10ac6ae..6df522c280 100644--- a/crates/router/src/types/domain/types.rs+++ b/crates/router/src/types/domain/types.rs@@ -1,4 +1,4 @@-use common_utils::types::keymanager::KeyManagerState;+use common_utils::types::keymanager::{KeyManagerMetricsContext, KeyManagerState};pub use hyperswitch_domain_models::type_encryption::{crypto_operation, AsyncLift, CryptoOperation, Lift, OptionalEncryptableJsonType,};@@ -31,6 +31,7 @@ impl ForeignFrom<(&app::AppState, configs::Tenant)> for KeyManagerState {ca: conf.ca.clone(),infra_values: app::AppState::process_env_mappings(app_state.conf.infra_values.clone()),use_legacy_key_store_decryption: conf.use_legacy_key_store_decryption,+ metrics_context: None,}}}@@ -55,6 +56,10 @@ impl From<&app::SessionState> for KeyManagerState {ca: conf.ca.clone(),infra_values: app::AppState::process_env_mappings(state.conf.infra_values.clone()),use_legacy_key_store_decryption: conf.use_legacy_key_store_decryption,+ metrics_context: state.payment_metrics_context.map(|context| {+ let merchant_mode: &'static str = context.merchant_mode.into();+ KeyManagerMetricsContext { merchant_mode }+ }),}}}diff --git a/crates/router_env/src/metrics.rs b/crates/router_env/src/metrics.rsindex c8dafedd25..4fe6c18ca2 100644--- a/crates/router_env/src/metrics.rs+++ b/crates/router_env/src/metrics.rs@@ -38,6 +38,18 @@ macro_rules! counter_metric {.build()});};+ ($name:ident, $meter:ident, name: $metric_name:literal, description: $description:literal, unit: $unit:literal $(,)?) => {+ #[doc = $description]+ pub(crate) static $name: ::std::sync::LazyLock<+ $crate::opentelemetry::metrics::Counter<u64>,+ > = ::std::sync::LazyLock::new(|| {+ $meter+ .u64_counter($metric_name)+ .with_description($description)+ .with_unit($unit)+ .build()+ });+ };}/// Create a [`Histogram`][Histogram] f64 metric with the specified name and an optional description,@@ -69,6 +81,19 @@ macro_rules! histogram_metric_f64 {.build()});};+ ($name:ident, $meter:ident, name: $metric_name:literal, description: $description:literal, unit: $unit:literal $(,)?) => {+ #[doc = $description]+ pub(crate) static $name: ::std::sync::LazyLock<+ $crate::opentelemetry::metrics::Histogram<f64>,+ > = ::std::sync::LazyLock::new(|| {+ $meter+ .f64_histogram($metric_name)+ .with_description($description)+ .with_unit($unit)+ .with_boundaries($crate::metrics::f64_histogram_buckets())+ .build()+ });+ };}/// Create a [`Histogram`][Histogram] u64 metric with the specified name and an optional description,