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(account_updater): emit synchronization observation event (#13514)
Kanika Bansal6c8a074291d5
diff --git a/config/config.example.toml b/config/config.example.tomlindex 4ade12713e..b42599c53f 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1294,6 +1294,7 @@ authentication_analytics_topic = "topic" # Kafka topic to be used for Authenticarouting_logs_topic = "topic" # Kafka topic to be used for Routing eventsrevenue_recovery_topic = "topic" # Kafka topic to be used for revenue recovery eventsexternal_service_call_topic = "topic" # Kafka topic to be used for external service call events+account_updater_topic = "topic" # Kafka topic to be used for account updater synchronization events# File storage configuration[file_storage]diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 1b98d2dc80..cc92efb63b 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -109,6 +109,7 @@ fraud_check_analytics_topic = "topic" # Kafka topic to be used for Fraud Checrouting_logs_topic = "topic" # Kafka topic to be used for Routing eventsrevenue_recovery_topic = "topic" # Kafka topic to be used for Revenue Recovery Eventsexternal_service_call_topic = "topic" # Kafka topic to be used for External Service Call Events+account_updater_topic = "topic" # Kafka topic to be used for Account Updater Synchronization Events# File storage configuration[file_storage]diff --git a/config/development.toml b/config/development.tomlindex b80e13525e..92bdfff433 100644--- a/config/development.toml+++ b/config/development.toml@@ -1426,6 +1426,7 @@ authentication_analytics_topic = "hyperswitch-authentication-events"routing_logs_topic = "hyperswitch-routing-api-events"revenue_recovery_topic = "hyperswitch-revenue-recovery-events"external_service_call_topic = "hyperswitch-external-service-call-events"+account_updater_topic = "hyperswitch-account-updater-events"[debit_routing_config]supported_currencies = "USD"diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 11eb17fc3c..0431848773 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1255,6 +1255,7 @@ authentication_analytics_topic = "hyperswitch-authentication-events"routing_logs_topic = "hyperswitch-routing-api-events"revenue_recovery_topic = "hyperswitch-revenue-recovery-events"external_service_call_topic = "hyperswitch-external-service-call-events"+account_updater_topic = "hyperswitch-account-updater-events"[analytics]source = "sqlx"diff --git a/crates/analytics/docs/clickhouse/scripts/account_updater_events.sql b/crates/analytics/docs/clickhouse/scripts/account_updater_events.sqlnew file mode 100644index 0000000000..880d94b1cf--- /dev/null+++ b/crates/analytics/docs/clickhouse/scripts/account_updater_events.sql@@ -0,0 +1,80 @@+CREATE TABLE account_updater_events_queue+(+ `request_id` Nullable(String),+ `merchant_id` String,+ `profile_id` String,+ `payment_method_id` String,+ `card_network` LowCardinality(Nullable(String)),+ `updater_outcome` LowCardinality(Nullable(String)),+ `error_category` LowCardinality(Nullable(String)),+ `latency_ms` UInt64,+ `created_at` DateTime64(9)+)+ENGINE = Kafka+SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-account-updater-events', kafka_group_name = 'hyper', kafka_format = 'JSONEachRow', kafka_handle_error_mode = 'stream';++CREATE MATERIALIZED VIEW account_updater_events_parse_errors (+ `topic` String,+ `partition` Int64,+ `offset` Int64,+ `raw` String,+ `error` String+) ENGINE = MergeTree+ORDER BY+ (topic, partition, offset) SETTINGS index_granularity = 8192 AS+SELECT+ _topic AS topic,+ _partition AS partition,+ _offset AS offset,+ _raw_message AS raw,+ _error AS error+FROM+ account_updater_events_queue+WHERE+ length(_error) > 0;++CREATE TABLE account_updater_events (+ `request_id` Nullable(String),+ `merchant_id` String,+ `profile_id` String,+ `payment_method_id` String,+ `card_network` LowCardinality(Nullable(String)),+ `updater_outcome` LowCardinality(Nullable(String)),+ `error_category` LowCardinality(Nullable(String)),+ `latency_ms` UInt64,+ `created_at` DateTime64(9),+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),+ INDEX paymentMethodIndex payment_method_id TYPE bloom_filter GRANULARITY 1,+ INDEX profileIndex profile_id TYPE bloom_filter GRANULARITY 1+) ENGINE = MergeTree+PARTITION BY toStartOfDay(created_at)+ORDER BY ( created_at, merchant_id, profile_id, payment_method_id )+SETTINGS index_granularity = 8192;++CREATE MATERIALIZED VIEW account_updater_events_mv TO account_updater_events (+ `request_id` Nullable(String),+ `merchant_id` String,+ `profile_id` String,+ `payment_method_id` String,+ `card_network` LowCardinality(Nullable(String)),+ `updater_outcome` LowCardinality(Nullable(String)),+ `error_category` LowCardinality(Nullable(String)),+ `latency_ms` UInt64,+ `created_at` DateTime64(9),+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4)+) AS+SELECT+ request_id,+ merchant_id,+ profile_id,+ payment_method_id,+ card_network,+ updater_outcome,+ error_category,+ latency_ms,+ created_at,+ now() AS inserted_at+FROM+ account_updater_events_queue+WHERE+ length(_error) = 0;diff --git a/crates/router/src/core/account_updater.rs b/crates/router/src/core/account_updater.rsindex c28273edbc..d225a5b638 100644--- a/crates/router/src/core/account_updater.rs+++ b/crates/router/src/core/account_updater.rs@@ -14,7 +14,10 @@ use self::{refresh::request_account_updater_refresh,types::{AccountUpdaterError, ResolvedAccountUpdaterConfig},};-use crate::{core::configs::dimension_state, routes::SessionState, types::domain};+use crate::{+ core::configs::dimension_state, events::account_updater as account_updater_events,+ routes::SessionState, types::domain,+};#[instrument(skip_all)]pub async fn run_account_updater<D>(@@ -39,6 +42,8 @@ pub async fn run_account_updater<D>(}};+ let started_at = std::time::Instant::now();+let outcome = refresh_stored_payment_method(state,platform,@@ -49,13 +54,24 @@ pub async fn run_account_updater<D>().await;- match outcome {+ match &outcome {Ok(refresh_outcome) => logger::info!(account_updater_outcome = refresh_outcome.as_str_name(),"Account Updater refresh completed"),Err(error) => logger::warn!(?error, "Account Updater refresh did not complete"),}++ let event = account_updater_events::KafkaAccountUpdaterEvent::new(+ state.request_id.as_ref().map(|id| id.to_string()),+ platform.get_processor().get_account().get_id(),+ profile.get_id(),+ payment_method,+ &outcome,+ started_at.elapsed().as_millis(),+ );++ state.event_handler.log_event(&event);}async fn refresh_stored_payment_method(diff --git a/crates/router/src/core/account_updater/types.rs b/crates/router/src/core/account_updater/types.rsindex 32c2ff6857..a24f337a0d 100644--- a/crates/router/src/core/account_updater/types.rs+++ b/crates/router/src/core/account_updater/types.rs@@ -112,7 +112,8 @@ impl From<&settings::AccountUpdaterConfig> for ResolvedAccountUpdaterConfig {}}-#[derive(Debug, thiserror::Error)]+#[derive(Debug, thiserror::Error, serde::Serialize)]+#[serde(rename_all = "snake_case")]pub enum AccountUpdaterError {#[error("Account Updater application config is missing or invalid")]MissingApplicationConfig,diff --git a/crates/router/src/events.rs b/crates/router/src/events.rsindex 0e4d59fc11..c1e7a771e9 100644--- a/crates/router/src/events.rs+++ b/crates/router/src/events.rs@@ -15,6 +15,8 @@ use crate::{services::kafka::{KafkaMessage, KafkaSettings},};+#[cfg(feature = "v2")]+pub mod account_updater;pub mod api_logs;pub mod audit_events;pub mod connector_api_logs;@@ -41,6 +43,7 @@ pub enum EventType {RoutingApiLogs,RevenueRecovery,ExternalServiceCall,+ AccountUpdater,}#[derive(Debug, Default, Deserialize, Clone)]diff --git a/crates/router/src/events/account_updater.rs b/crates/router/src/events/account_updater.rsnew file mode 100644index 0000000000..a02a553425--- /dev/null+++ b/crates/router/src/events/account_updater.rs@@ -0,0 +1,73 @@+use common_enums::CardNetwork;+use common_utils::{errors::CustomResult, id_type};+use hyperswitch_domain_models::payment_method_data::PaymentMethodsData;+use serde::Serialize;+use time::OffsetDateTime;+use unified_connector_service_client::payments as payments_grpc;++use super::EventType;+use crate::{+ core::account_updater::types::AccountUpdaterError, services::kafka::KafkaMessage, types::domain,+};++#[derive(Debug, Serialize)]+pub struct KafkaAccountUpdaterEvent<'a> {+ pub request_id: Option<String>,+ pub merchant_id: &'a id_type::MerchantId,+ pub profile_id: &'a id_type::ProfileId,+ pub payment_method_id: &'a id_type::GlobalPaymentMethodId,+ pub card_network: Option<CardNetwork>,+ pub updater_outcome: Option<&'static str>,+ pub error_category: Option<&'a AccountUpdaterError>,+ pub latency_ms: u128,+ pub created_at: i128,+}++impl<'a> KafkaAccountUpdaterEvent<'a> {+ pub fn new(+ request_id: Option<String>,+ merchant_id: &'a id_type::MerchantId,+ profile_id: &'a id_type::ProfileId,+ payment_method: &'a domain::PaymentMethod,+ evaluation: &'a CustomResult<payments_grpc::CardRefreshOutcome, AccountUpdaterError>,+ latency_ms: u128,+ ) -> Self {+ let (updater_outcome, error_category) = match evaluation {+ Ok(outcome) => (Some(outcome.as_str_name()), None),+ Err(error) => (None, Some(error.current_context())),+ };++ Self {+ request_id,+ merchant_id,+ profile_id,+ payment_method_id: payment_method.get_id(),+ card_network: stored_card_network(payment_method),+ updater_outcome,+ error_category,+ latency_ms,+ created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(),+ }+ }+}++fn stored_card_network(payment_method: &domain::PaymentMethod) -> Option<CardNetwork> {+ match payment_method+ .payment_method_data+ .as_ref()+ .map(|payment_method_data| payment_method_data.get_inner())+ {+ Some(PaymentMethodsData::Card(card_details)) => card_details.card_network.clone(),+ _ => None,+ }+}++impl KafkaMessage for KafkaAccountUpdaterEvent<'_> {+ fn key(&self) -> String {+ self.payment_method_id.get_string_repr().to_owned()+ }++ fn event_type(&self) -> EventType {+ EventType::AccountUpdater+ }+}diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rsindex 12f5b20116..cfd7afc1e6 100644--- a/crates/router/src/services/kafka.rs+++ b/crates/router/src/services/kafka.rs@@ -166,6 +166,7 @@ pub struct KafkaSettings {routing_logs_topic: String,revenue_recovery_topic: String,external_service_call_topic: String,+ account_updater_topic: String,}/// Base rdkafka client configuration for this deployment's Kafka cluster.@@ -281,6 +282,12 @@ impl KafkaSettings {))})?;+ common_utils::fp_utils::when(self.account_updater_topic.is_default_or_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "Kafka Account Updater topic must not be empty".into(),+ ))+ })?;+Ok(())}@@ -322,6 +329,7 @@ pub struct KafkaProducer {routing_logs_topic: String,revenue_recovery_topic: String,external_service_call_topic: String,+ account_updater_topic: String,}struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>);@@ -372,6 +380,7 @@ impl KafkaProducer {routing_logs_topic: conf.routing_logs_topic.clone(),revenue_recovery_topic: conf.revenue_recovery_topic.clone(),external_service_call_topic: conf.external_service_call_topic.clone(),+ account_updater_topic: conf.account_updater_topic.clone(),})}@@ -712,6 +721,7 @@ impl KafkaProducer {EventType::RoutingApiLogs => &self.routing_logs_topic,EventType::RevenueRecovery => &self.revenue_recovery_topic,EventType::ExternalServiceCall => &self.external_service_call_topic,+ EventType::AccountUpdater => &self.account_updater_topic,}}}