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(payment_methods): add metrics for modular payment method service (#13685)
Shankar Singh C78cd8a1bf401
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex d511f90074..44343bf782 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -79,6 +79,8 @@ use super::{pm_auth,};#[cfg(feature = "v2")]+use crate::routes::metrics;+#[cfg(feature = "v2")]use crate::{configs::settings,core::{@@ -6676,11 +6678,14 @@ pub async fn payment_methods_session_create(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Unable to generate GlobalPaymentMethodSessionId")?;- let encrypted_data = request- .encrypt_data(key_manager_state, platform.get_provider().get_key_store())- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to encrypt payment methods session data")?;+ let encrypted_data = common_utils::metrics::utils::record_operation_time(+ request.encrypt_data(key_manager_state, platform.get_provider().get_key_store()),+ &metrics::PAYMENT_METHOD_CRYPTO_DURATION,+ router_env::metric_attributes!(("operation", "encrypt")),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encrypt payment methods session data")?;let billing = encrypted_data.billing@@ -6804,11 +6809,14 @@ pub async fn payment_methods_session_update(}).attach_printable("Failed to retrieve payment methods session from db")?;- let encrypted_data = request- .encrypt_data(key_manager_state, provider.get_key_store())- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to encrypt payment methods session data")?;+ let encrypted_data = common_utils::metrics::utils::record_operation_time(+ request.encrypt_data(key_manager_state, provider.get_key_store()),+ &metrics::PAYMENT_METHOD_CRYPTO_DURATION,+ router_env::metric_attributes!(("operation", "encrypt")),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encrypt payment methods session data")?;let billing = encrypted_data.billingdiff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 604b903c5f..98679a3d3c 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -3062,14 +3062,18 @@ pub async fn decode_and_decrypt_locker_data(.change_context(errors::VaultError::ResponseDeserializationFailed).attach_printable("Failed to decode hex string into bytes")?;// Decrypt- domain::types::crypto_operation(- &state.into(),- type_name!(payment_method::PaymentMethod),- domain::types::CryptoOperation::DecryptOptional(Some(Encryption::new(- decoded_bytes.into(),- ))),- Identifier::Merchant(key_store.merchant_id.clone()),- key,+ common_utils::metrics::utils::record_operation_time(+ domain::types::crypto_operation(+ &state.into(),+ type_name!(payment_method::PaymentMethod),+ domain::types::CryptoOperation::DecryptOptional(Some(Encryption::new(+ decoded_bytes.into(),+ ))),+ Identifier::Merchant(key_store.merchant_id.clone()),+ key,+ ),+ &metrics::PAYMENT_METHOD_CRYPTO_DURATION,+ router_env::metric_attributes!(("operation", "decrypt")),).await.and_then(|val| val.try_into_optionaloperation())@@ -6195,19 +6199,22 @@ where{let key = key_store.key.get_inner().peek();let identifier = Identifier::Merchant(key_store.merchant_id.clone());- let decrypted_data =+ let decrypted_data = common_utils::metrics::utils::record_operation_time(domain::types::crypto_operation::<serde_json::Value, hyperswitch_masking::WithType>(&state.into(),type_name!(T),domain::types::CryptoOperation::DecryptOptional(data),identifier,key,- )- .await- .and_then(|val| val.try_into_optionaloperation())- .change_context(errors::StorageError::DecryptionError)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("unable to decrypt data")?;+ ),+ &metrics::PAYMENT_METHOD_CRYPTO_DURATION,+ router_env::metric_attributes!(("operation", "decrypt")),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ .change_context(errors::StorageError::DecryptionError)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("unable to decrypt data")?;decrypted_data.map(|decrypted_data| decrypted_data.into_inner().expose())diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex a64f607d9b..13e1fac765 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -2022,6 +2022,19 @@ async fn create_vault_request<R: pm_types::VaultingInterface>(Ok(request)}+/// Maps a vault flow name (`V::get_vaulting_flow_name()`) to its dedicated latency histogram.+/// Falls back to `VAULT_ADD_TIME` for flows without a dedicated histogram (e.g. entity creation).+fn vault_operation_latency_metric(+ flow_name: &str,+) -> &'static router_env::opentelemetry::metrics::Histogram<f64> {+ match flow_name {+ consts::V2_VAULT_RETRIEVE_FLOW_TYPE => &metrics::VAULT_GET_TIME,+ consts::V2_VAULT_DELETE_FLOW_TYPE => &metrics::VAULT_DELETE_TIME,+ consts::V2_VAULT_GET_FINGERPRINT_FLOW_TYPE => &metrics::VAULT_FINGERPRINT_TIME,+ _ => &metrics::VAULT_ADD_TIME,+ }+}+#[instrument(skip_all)]pub async fn call_to_vault<V: pm_types::VaultingInterface>(state: &routes::SessionState,@@ -2053,9 +2066,18 @@ pub async fn call_to_vault<V: pm_types::VaultingInterface>(Some(additional_headers),).await?;- let response = services::call_connector_api(state, request, V::get_vaulting_flow_name(), None)- .await- .change_context(errors::VaultError::VaultAPIError);+ let flow_name = V::get_vaulting_flow_name();+ let response = common_utils::metrics::utils::record_operation_time(+ services::call_connector_api(state, request, flow_name, None),+ vault_operation_latency_metric(flow_name),+ router_env::metric_attributes!(("operation", flow_name)),+ )+ .await+ .change_context(errors::VaultError::VaultAPIError)+ .inspect_err(|_| {+ metrics::VAULT_CALL_FAILURES+ .add(1, router_env::metric_attributes!(("operation", flow_name)));+ });let jwe_body: services::JweBody = response.get_response_inner("JweBody")diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex 437b79ff52..9dfcc2605f 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -159,3 +159,23 @@ counter_metric!(MERCHANT_ADVICE_CODE_CONFIG_MISS, GLOBAL_METER);// Config Fetch Metricscounter_metric!(CONFIG_DATABASE_FETCH, GLOBAL_METER); // When fetched from databasecounter_metric!(CONFIG_DEFAULT_FALLBACK, GLOBAL_METER); // When defaulted to application default++// Payment Method (modular service) business-level metrics+counter_metric!(PAYMENT_METHOD_OPS_COUNT, GLOBAL_METER);+histogram_metric_f64!(PAYMENT_METHOD_OPERATION_DURATION, GLOBAL_METER);++counter_metric!(PAYMENT_METHOD_SESSION_OPS_COUNT, GLOBAL_METER);+histogram_metric_f64!(PAYMENT_METHOD_SESSION_OPERATION_DURATION, GLOBAL_METER);+counter_metric!(SUCCESSFUL_PAYMENT_METHOD_SESSION_CONFIRM, GLOBAL_METER);++// v2 vault call latency (payment_methods modular service) - distinct from the+// v1-only CARD_ADD_TIME/CARD_GET_TIME/CARD_DELETE_TIME, which instrument the+// legacy add_card_to_locker/delete_card_from_locker functions, not vault::call_to_vault.+histogram_metric_f64!(VAULT_ADD_TIME, GLOBAL_METER);+histogram_metric_f64!(VAULT_GET_TIME, GLOBAL_METER);+histogram_metric_f64!(VAULT_DELETE_TIME, GLOBAL_METER);+histogram_metric_f64!(VAULT_FINGERPRINT_TIME, GLOBAL_METER);+counter_metric!(VAULT_CALL_FAILURES, GLOBAL_METER);++// Encryption/keymanager latency for payment_methods operations+histogram_metric_f64!(PAYMENT_METHOD_CRYPTO_DURATION, GLOBAL_METER);diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex f80694cdee..0eb4dbbb43 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -22,6 +22,8 @@ pub use migrate::modular_migrate_payment_methods;use router_env::{instrument, logger, tracing, Flow};use super::app::{AppState, SessionState};+#[cfg(feature = "v2")]+use super::metrics;#[cfg(feature = "v1")]use crate::core::utils::validate_legacy_endpoint_access;#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]@@ -43,6 +45,64 @@ use crate::{},};+/// Records `PAYMENT_METHOD_SESSION_OPERATION_DURATION`/`PAYMENT_METHOD_SESSION_OPS_COUNT` around a+/// `payment_method_session` core call, tagged by `operation` and success/error `outcome`. Also bumps+/// `SUCCESSFUL_PAYMENT_METHOD_SESSION_CONFIRM` on a successful `session_confirm` call, since that flow+/// is the closest equivalent to a completed payment for this service.+#[cfg(feature = "v2")]+async fn record_payment_method_session_metrics<T, E>(+ operation: &'static str,+ fut: impl std::future::Future<Output = Result<T, E>>,+) -> Result<T, E> {+ let result = common_utils::metrics::utils::record_operation_time(+ fut,+ &metrics::PAYMENT_METHOD_SESSION_OPERATION_DURATION,+ router_env::metric_attributes!(("operation", operation)),+ )+ .await;++ metrics::PAYMENT_METHOD_SESSION_OPS_COUNT.add(+ 1,+ router_env::metric_attributes!(+ ("operation", operation),+ ("outcome", if result.is_ok() { "success" } else { "error" })+ ),+ );++ if operation == "session_confirm" && result.is_ok() {+ metrics::SUCCESSFUL_PAYMENT_METHOD_SESSION_CONFIRM.add(1, &[]);+ }++ result+}++/// Records `PAYMENT_METHOD_OPERATION_DURATION`/`PAYMENT_METHOD_OPS_COUNT` around a top-level+/// `payment_methods` core call, tagged by `operation` and success/error `outcome`. Use this for+/// route handlers whose core call is a trait method (e.g. `PaymentMethodsController`) that can't+/// be wrapped at its definition the way the plain core functions in `core/payment_methods.rs` are.+#[cfg(feature = "v2")]+async fn record_payment_method_metrics<T, E>(+ operation: &'static str,+ fut: impl std::future::Future<Output = Result<T, E>>,+) -> Result<T, E> {+ let result = common_utils::metrics::utils::record_operation_time(+ fut,+ &metrics::PAYMENT_METHOD_OPERATION_DURATION,+ router_env::metric_attributes!(("operation", operation)),+ )+ .await;++ metrics::PAYMENT_METHOD_OPS_COUNT.add(+ 1,+ router_env::metric_attributes!(+ ("operation", operation),+ ("outcome", if result.is_ok() { "success" } else { "error" })+ ),+ );++ result+}+#[cfg(feature = "v1")]#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]pub async fn create_payment_method_api(@@ -106,13 +166,16 @@ pub async fn create_payment_method_api(&req,json_payload.into_inner(),|state, auth: auth::AuthenticationData, req, req_state| async move {- Box::pin(payment_methods_routes::create_payment_method(- &state,- &req_state,- req,- &auth.platform,- &auth.profile,- ))+ record_payment_method_metrics(+ "create",+ Box::pin(payment_methods_routes::create_payment_method(+ &state,+ &req_state,+ req,+ &auth.platform,+ &auth.profile,+ )),+ ).await},&*auth_type,@@ -243,12 +306,15 @@ pub async fn payment_method_update_api(&req,payload,|state, auth: auth::AuthenticationData, req, _| {- payment_methods_routes::update_payment_method(- state,- auth.platform,- auth.profile,- req,- &payment_method_id,+ record_payment_method_metrics(+ "update",+ payment_methods_routes::update_payment_method(+ state,+ auth.platform,+ auth.profile,+ req,+ &payment_method_id,+ ),)},&*auth_type,@@ -291,13 +357,16 @@ pub async fn payment_method_retrieve_api(&req,payload,|state, auth: auth::AuthenticationData, pm, _| {- payment_methods_routes::retrieve_payment_method(- state,- pm,- auth.profile,- auth.platform,- api_key_type,- query_payload.fetch_raw_detail,+ record_payment_method_metrics(+ "retrieve",+ payment_methods_routes::retrieve_payment_method(+ state,+ pm,+ auth.profile,+ auth.platform,+ api_key_type,+ query_payload.fetch_raw_detail,+ ),)},&*auth_type,@@ -339,7 +408,15 @@ pub async fn payment_method_delete_api(&req,payload,|state, auth: auth::AuthenticationData, pm, _| {- payment_methods_routes::delete_payment_method(state, pm, auth.platform, auth.profile)+ record_payment_method_metrics(+ "delete",+ payment_methods_routes::delete_payment_method(+ state,+ pm,+ auth.platform,+ auth.profile,+ ),+ )},&*auth_type,api_locking::LockAction::NotApplicable,@@ -909,11 +986,14 @@ pub async fn list_customer_payment_method_api(&req,payload,|state, auth: auth::AuthenticationData, payload, _| {- payment_methods_routes::list_saved_payment_methods_for_customer(- state,- auth.platform.get_provider().clone(),- customer_id.clone(),- payload.include_new.unwrap_or(false),+ record_payment_method_metrics(+ "list_saved_payment_methods",+ payment_methods_routes::list_saved_payment_methods_for_customer(+ state,+ auth.platform.get_provider().clone(),+ customer_id.clone(),+ payload.include_new.unwrap_or(false),+ ),)},&*auth_type,@@ -1374,15 +1454,18 @@ pub async fn default_payment_method_set_api(default_payment_method.payment_method_id.clone(),);async move {- cards::PmCards {- state: &state,- provider: auth.platform.get_provider(),- }- .set_default_payment_method(- auth.platform.get_provider().get_account().get_id(),- &customer_id,- &payment_method_id,- auth.platform.get_initiator(),+ record_payment_method_metrics(+ "set_default",+ cards::PmCards {+ state: &state,+ provider: auth.platform.get_provider(),+ }+ .set_default_payment_method(+ auth.platform.get_provider().get_account().get_id(),+ &customer_id,+ &payment_method_id,+ auth.platform.get_initiator(),+ ),).await}@@ -1692,12 +1775,15 @@ pub async fn payment_methods_session_create(&req,payload,|state, auth: auth::AuthenticationData, request, _| async move {- Box::pin(payment_methods_routes::payment_methods_session_create(- state,- auth.platform,- auth.profile,- request,- ))+ record_payment_method_session_metrics(+ "session_create",+ Box::pin(payment_methods_routes::payment_methods_session_create(+ state,+ auth.platform,+ auth.profile,+ request,+ )),+ ).await},&*auth_type,@@ -1725,12 +1811,15 @@ pub async fn payment_methods_session_update(|state, auth: auth::AuthenticationData, req, _| {let value = payment_method_session_id.clone();async move {- payment_methods_routes::payment_methods_session_update(- state,- auth.platform.get_provider().clone(),- value.clone(),- req,- )+ Box::pin(record_payment_method_session_metrics(+ "session_update",+ payment_methods_routes::payment_methods_session_update(+ state,+ auth.platform.get_provider().clone(),+ value.clone(),+ req,+ ),+ )).await}},@@ -1759,10 +1848,13 @@ pub async fn payment_methods_session_retrieve(&req,payment_method_session_id.clone(),|state, auth: auth::AuthenticationData, payment_method_session_id, _| async move {- payment_methods_routes::payment_methods_session_retrieve(- state,- auth.platform.get_provider().clone(),- payment_method_session_id,+ record_payment_method_session_metrics(+ "session_retrieve",+ payment_methods_routes::payment_methods_session_retrieve(+ state,+ auth.platform.get_provider().clone(),+ payment_method_session_id,+ ),).await},@@ -1806,11 +1898,14 @@ pub async fn payment_method_session_list_payment_methods(&req,payment_method_session_id.clone(),|state, auth: auth::AuthenticationData, payment_method_session_id, _| {- payment_methods_routes::list_payment_methods_for_session(- state,- auth.platform,- auth.profile,- payment_method_session_id,+ record_payment_method_session_metrics(+ "session_list_payment_methods",+ payment_methods_routes::list_payment_methods_for_session(+ state,+ auth.platform,+ auth.profile,+ payment_method_session_id,+ ),)},auth::sdk_or_client_auth(@@ -1875,13 +1970,16 @@ pub async fn payment_method_session_confirm(&req,request,|state, auth: auth::AuthenticationData, request, req_state| {- payment_methods_routes::payment_methods_session_confirm(- state,- req_state,- auth.platform,- auth.profile,- request.payment_method_session_id,- request.request,+ record_payment_method_session_metrics(+ "session_confirm",+ payment_methods_routes::payment_methods_session_confirm(+ state,+ req_state,+ auth.platform,+ auth.profile,+ request.payment_method_session_id,+ request.request,+ ),)},auth::sdk_or_client_auth(@@ -1929,12 +2027,15 @@ pub async fn payment_method_session_update_saved_payment_method(&req,request,|state, auth: auth::AuthenticationData, request, _| {- payment_methods_routes::payment_methods_session_update_payment_method(- state,- auth.platform,- auth.profile,- request.payment_method_session_id,- request.request,+ record_payment_method_session_metrics(+ "session_update_saved_pm",+ payment_methods_routes::payment_methods_session_update_payment_method(+ state,+ auth.platform,+ auth.profile,+ request.payment_method_session_id,+ request.request,+ ),)},auth::sdk_or_client_auth(@@ -1982,12 +2083,15 @@ pub async fn payment_method_session_delete_saved_payment_method(&req,request,|state, auth: auth::AuthenticationData, request, _| {- payment_methods_routes::payment_methods_session_delete_payment_method(- state,- auth.platform,- auth.profile,- request.request.payment_method_token,- request.payment_method_session_id,+ record_payment_method_session_metrics(+ "session_delete_saved_pm",+ payment_methods_routes::payment_methods_session_delete_payment_method(+ state,+ auth.platform,+ auth.profile,+ request.request.payment_method_token,+ request.payment_method_session_id,+ ),)},auth::sdk_or_client_auth(@@ -2074,11 +2178,14 @@ pub async fn payment_method_get_token_details_api(let temporary_token = temporary_token.clone();async move {let platform: domain::Platform = auth.platform;- payment_methods_routes::payment_method_get_token_details_core(- state,- platform.get_provider().clone(),- temporary_token,- )+ Box::pin(record_payment_method_metrics(+ "get_token_details",+ payment_methods_routes::payment_method_get_token_details_core(+ state,+ platform.get_provider().clone(),+ temporary_token,+ ),+ )).await}},