Skip to content

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

fix(core): add fix for stopping multiple event locking idempotent logs (#8034)

Debarati Ghatak312c7337e8e7
diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs
index a06fe6ff61..e9a0b76045 100644
--- a/crates/diesel_models/src/query/events.rs
+++ b/crates/diesel_models/src/query/events.rs
@@ -32,6 +32,20 @@ impl Event {
.await
}
+ pub async fn find_by_merchant_id_idempotent_event_id(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::idempotent_event_id.eq(idempotent_event_id.to_owned())),
+ )
+ .await
+ }
+
pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index baa5b4af58..34b49c2fc8 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -155,10 +155,10 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
if (state
.store
- .find_event_by_merchant_id_event_id(
+ .find_event_by_merchant_id_idempotent_event_id(
key_manager_state,
&merchant_id,
- &event_id,
+ &idempotent_event_id,
merchant_context.get_merchant_key_store(),
)
.await)
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index f8beab284c..df3293714f 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -38,6 +38,14 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
+ async fn find_event_by_merchant_id_idempotent_event_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError>;
+
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
@@ -157,6 +165,31 @@ impl EventInterface for Store {
.change_context(errors::StorageError::DecryptionError)
}
+ #[instrument(skip_all)]
+ async fn find_event_by_merchant_id_idempotent_event_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::find_by_merchant_id_idempotent_event_id(
+ &conn,
+ merchant_id,
+ idempotent_event_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
@@ -460,6 +493,40 @@ impl EventInterface for MockDb {
)
}
+ async fn find_event_by_merchant_id_idempotent_event_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+ locked_events
+ .iter()
+ .find(|event| {
+ event.merchant_id == Some(merchant_id.to_owned()) && event.idempotent_event_id == Some(idempotent_event_id.to_string())
+ })
+ .cloned()
+ .async_map(|event| async {
+ event
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ .transpose()?
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No event available with merchant_id = {merchant_id:?} and idempotent_event_id = {idempotent_event_id}"
+ ))
+ .into(),
+ )
+ }
+
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
@@ -777,11 +844,24 @@ impl EventInterface for MockDb {
mod tests {
use std::sync::Arc;
- use common_utils::{type_name, types::keymanager::Identifier};
- use diesel_models::{enums, events::EventMetadata};
+ use api_models::webhooks as api_webhooks;
+ use common_enums::IntentStatus;
+ use common_utils::{
+ generate_organization_id_of_default_length, type_name,
+ types::{keymanager::Identifier, MinorUnit},
+ };
+ use diesel_models::{
+ business_profile::WebhookDetails,
+ enums::{self},
+ events::EventMetadata,
+ };
+ use futures::future::join_all;
+ use hyperswitch_domain_models::merchant_account::MerchantAccountSetter;
use time::macros::datetime;
+ use tokio::time::{timeout, Duration};
use crate::{
+ core::webhooks as webhooks_core,
db::{
events::EventInterface, merchant_key_store::MerchantKeyStoreInterface,
MasterKeyInterface, MockDb,
@@ -791,7 +871,10 @@ mod tests {
app::{settings::Settings, StorageImpl},
},
services,
- types::domain,
+ types::{
+ api,
+ domain::{self, MerchantAccount},
+ },
};
#[allow(clippy::unwrap_used)]
@@ -1027,4 +1110,357 @@ mod tests {
assert_eq!(updated_event.primary_object_id, payment_id);
assert_eq!(updated_event.event_id, event_id);
}
+
+ #[cfg(feature = "v1")]
+ #[allow(clippy::panic_in_result_fn)]
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn test_concurrent_webhook_insertion_with_redis_lock(
+ ) -> Result<(), Box<dyn std::error::Error>> {
+ // Test concurrent webhook insertion with a Redis lock to prevent race conditions
+ let conf = Settings::new()?;
+ let tx: tokio::sync::oneshot::Sender<()> = tokio::sync::oneshot::channel().0;
+
+ let app_state = Box::pin(routes::AppState::with_storage(
+ conf,
+ StorageImpl::PostgresqlTest,
+ tx,
+ Box::new(services::MockApiClient),
+ ))
+ .await;
+
+ let tenant_id = common_utils::id_type::TenantId::try_from_string("public".to_string())?;
+
+ let state = Arc::new(app_state)
+ .get_session_state(&tenant_id, None, || {})
+ .map_err(|_| "failed to get session state")?;
+
+ let merchant_id =
+ common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("juspay_merchant"))?;
+ let business_profile_id =
+ common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1"))?;
+ let key_manager_state = &(&state).into();
+ let master_key = state.store.get_master_key();
+
+ let aes_key = services::generate_aes256_key()?;
+
+ let merchant_key_store = state
+ .store
+ .insert_merchant_key_store(
+ key_manager_state,
+ domain::MerchantKeyStore {
+ merchant_id: merchant_id.clone(),
+ key: domain::types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::MerchantKeyStore),
+ domain::types::CryptoOperation::Encrypt(aes_key.to_vec().into()),
+ Identifier::Merchant(merchant_id.to_owned()),
+ master_key,
+ )
+ .await?
+ .try_into_operation()?,
+ created_at: datetime!(2023-02-01 0:00),
+ },
+ &master_key.to_vec().into(),
+ )
+ .await?;
+
+ let merchant_account_to_insert = MerchantAccount::from(MerchantAccountSetter {
+ merchant_id: merchant_id.clone(),
+ merchant_name: None,
+ merchant_details: None,
+ return_url: None,
+ webhook_details: Some(WebhookDetails {
+ webhook_version: None,
+ webhook_username: None,
+ webhook_password: None,
+ webhook_url: Some(masking::Secret::new(
+ "https://example.com/webhooks".to_string(),
+ )),
+ payment_created_enabled: None,
+ payment_succeeded_enabled: Some(true),
+ payment_failed_enabled: None,
+ payment_statuses_enabled: None,
+ refund_statuses_enabled: None,
+ payout_statuses_enabled: None,
+ }),
+ sub_merchants_enabled: None,
+ parent_merchant_id: None,
+ enable_payment_response_hash: true,
+ payment_response_hash_key: None,
+ redirect_to_merchant_with_http_post: false,
+ publishable_key: "pk_test_11DviC2G2fb3lAJoes1q3A2222233327".to_string(),
+ locker_id: None,
+ storage_scheme: enums::MerchantStorageScheme::PostgresOnly,
+ metadata: None,
+ routing_algorithm: None,
+ primary_business_details: serde_json::json!({ "country": "US", "business": "default" }),
+ intent_fulfillment_time: Some(1),
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ frm_routing_algorithm: None,
+ payout_routing_algorithm: None,
+ organization_id: generate_organization_id_of_default_length(),
+ is_recon_enabled: true,
+ default_profile: None,
+ recon_status: enums::ReconStatus::NotRequested,
+ payment_link_config: None,
+ pm_collect_link_config: None,
+ is_platform_account: false,
+ merchant_account_type: common_enums::MerchantAccountType::Standard,
+ product_type: None,
+ version: common_enums::ApiVersion::V1,
+ });
+ let merchant_account = state
+ .store
+ .insert_merchant(
+ key_manager_state,
+ merchant_account_to_insert,
+ &merchant_key_store,
+ )
+ .await?;
+
+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
+ merchant_account,
+ merchant_key_store.clone(),
+ )));
+ let merchant_id = merchant_id.clone(); // Clone merchant_id to avoid move
+
+ let business_profile_to_insert = domain::Profile::from(domain::ProfileSetter {
+ merchant_country_code: None,
+ profile_id: business_profile_id.clone(),
+ merchant_id: merchant_id.clone(),
+ profile_name: "test_concurrent_profile".to_string(),
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ return_url: None,
+ enable_payment_response_hash: true,
+ payment_response_hash_key: None,
+ redirect_to_merchant_with_http_post: false,
+ webhook_details: Some(WebhookDetails {
+ webhook_version: None,
+ webhook_username: None,
+ webhook_password: None,
+ webhook_url: Some(masking::Secret::new(
+ "https://example.com/webhooks".to_string(),
+ )),
+ payment_created_enabled: None,
+ payment_succeeded_enabled: Some(true),
+ payment_failed_enabled: None,
+ payment_statuses_enabled: None,
+ refund_statuses_enabled: None,
+ payout_statuses_enabled: None,
+ }),
+ metadata: None,
+ routing_algorithm: None,
+ intent_fulfillment_time: None,
+ frm_routing_algorithm: None,
+ payout_routing_algorithm: None,
+ is_recon_enabled: false,
+ applepay_verified_domains: None,
+ payment_link_config: None,
+ session_expiry: None,
+ authentication_connector_details: None,
+ payout_link_config: None,
+ is_extended_card_info_enabled: None,
+ extended_card_info_config: None,
+ is_connector_agnostic_mit_enabled: None,
+ use_billing_as_payment_method_billing: None,
+ collect_shipping_details_from_wallet_connector: None,
+ collect_billing_details_from_wallet_connector: None,
+ outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
+ tax_connector_id: None,
+ is_tax_connector_enabled: false,
+ dynamic_routing_algorithm: None,
+ is_network_tokenization_enabled: false,
+ is_auto_retries_enabled: false,
+ max_auto_retries_enabled: None,
+ always_request_extended_authorization: None,
+ is_click_to_pay_enabled: false,
+ authentication_product_ids: None,
+ card_testing_guard_config: None,
+ card_testing_secret_key: None,
+ is_clear_pan_retries_enabled: false,
+ force_3ds_challenge: false,
+ is_debit_routing_enabled: false,
+ merchant_business_country: None,
+ is_iframe_redirection_enabled: None,
+ is_pre_network_tokenization_enabled: false,
+ merchant_category_code: None,
+ });
+
+ let business_profile = state
+ .store
+ .insert_business_profile(
+ key_manager_state,
+ &merchant_key_store.clone(),
+ business_profile_to_insert,
+ )
+ .await?;
+
+ // Same inputs for all threads
+ let event_type = enums::EventType::PaymentSucceeded;
+ let event_class = enums::EventClass::Payments;
+ let primary_object_id = Arc::new("concurrent_payment_id".to_string());
+ let primary_object_type = enums::EventObjectType::PaymentDetails;
+ let payment_id = common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Borrowed(
+ "pay_mbabizu24mvu3mela5njyhpit10",
+ ))?;
+
+ let primary_object_created_at = Some(common_utils::date_time::now());
+ let expected_response = api::PaymentsResponse {
+ payment_id,
+ status: IntentStatus::Succeeded,
+ amount: MinorUnit::new(6540),
+ amount_capturable: MinorUnit::new(0),
+ amount_received: None,
+ client_secret: None,
+ created: None,
+ currency: "USD".to_string(),
+ customer_id: None,
+ description: Some("Its my first payment request".to_string()),
+ refunds: None,
+ mandate_id: None,
+ merchant_id,
+ net_amount: MinorUnit::new(6540),
+ connector: None,
+ customer: None,
+ disputes: None,
+ attempts: None,
+ captures: None,
+ mandate_data: None,
+ setup_future_usage: None,
+ off_session: None,
+ capture_on: None,
+ capture_method: None,
+ payment_method: None,
+ payment_method_data: None,
+ payment_token: None,
+ shipping: None,
+ billing: None,
+ order_details: None,
+ email: None,
+ name: None,
+ phone: None,
+ return_url: None,
+ authentication_type: None,
+ statement_descriptor_name: None,
+ statement_descriptor_suffix: None,
+ next_action: None,
+ cancellation_reason: None,
+ error_code: None,
+ error_message: None,
+ unified_code: None,
+ unified_message: None,
+ payment_experience: None,
+ payment_method_type: None,
+ connector_label: None,
+ business_country: None,
+ business_label: None,
+ business_sub_label: None,
+ allowed_payment_method_types: None,
+ ephemeral_key: None,
+ manual_retry_allowed: None,
+ connector_transaction_id: None,
+ frm_message: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ reference_id: None,
+ payment_link: None,
+ profile_id: None,
+ surcharge_details: None,
+ attempt_count: 1,
+ merchant_decision: None,
+ merchant_connector_id: None,
+ incremental_authorization_allowed: None,
+ authorization_count: None,
+ incremental_authorizations: None,
+ external_authentication_details: None,
+ external_3ds_authentication_attempted: None,
+ expires_on: None,
+ fingerprint: None,
+ browser_info: None,
+ payment_method_id: None,
+ payment_method_status: None,
+ updated: None,
+ split_payments: None,
+ frm_metadata: None,
+ merchant_order_reference_id: None,
+ capture_before: None,
+ extended_authorization_applied: None,
+ order_tax_amount: None,
+ connector_mandate_id: None,
+ shipping_cost: None,
+ card_discovery: None,
+ force_3ds_challenge: None,
+ force_3ds_challenge_trigger: None,
+ issuer_error_code: None,
+ issuer_error_message: None,
+ is_iframe_redirection_enabled: None,
+ whole_connector_response: None,
+ payment_channel: None,
+ };
+ let content =
+ api_webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(expected_response));
+
+ // Run 10 concurrent webhook creations
+ let mut handles = vec![];
+ for _ in 0..10 {
+ let state_clone = state.clone();
+ let merchant_context_clone = merchant_context.clone();
+ let business_profile_clone = business_profile.clone();
+ let content_clone = content.clone();
+ let primary_object_id_clone = primary_object_id.clone();
+
+ let handle = tokio::spawn(async move {
+ webhooks_core::create_event_and_trigger_outgoing_webhook(
+ state_clone,
+ merchant_context_clone,
+ business_profile_clone,
+ event_type,
+ event_class,
+ (*primary_object_id_clone).to_string(),
+ primary_object_type,
+ content_clone,
+ primary_object_created_at,
+ )
+ .await
+ .map_err(|e| format!("create_event_and_trigger_outgoing_webhook failed: {e}"))
+ });
+
+ handles.push(handle);
+ }
+
+ // Await all tasks
+ // We give the whole batch 20 s; if they don't finish something is wrong.
+ let results = timeout(Duration::from_secs(20), join_all(handles))
+ .await
+ .map_err(|_| "tasks hung for >20 s – possible dead-lock / endless retry")?;
+
+ for res in results {
+ // Any task that panicked or returned Err will make the test fail here.
+ let _ = res.map_err(|e| format!("task panicked: {e}"))?;
+ }
+
+ // Collect all initial-attempt events for this payment
+ let events = state
+ .store
+ .list_initial_events_by_merchant_id_primary_object_id(
+ key_manager_state,
+ &business_profile.merchant_id,
+ &primary_object_id.clone(),
+ merchant_context.get_merchant_key_store(),
+ )
+ .await?;
+
+ assert_eq!(
+ events.len(),
+ 1,
+ "Expected exactly 1 row in events table, found {}",
+ events.len()
+ );
+ Ok(())
+ }
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 412cc0a4a1..ed9d140d22 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -746,6 +746,23 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn find_event_by_merchant_id_idempotent_event_id(
+ &self,
+ state: &KeyManagerState,
+ merchant_id: &id_type::MerchantId,
+ idempotent_event_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::Event, errors::StorageError> {
+ self.diesel_store
+ .find_event_by_merchant_id_idempotent_event_id(
+ state,
+ merchant_id,
+ idempotent_event_id,
+ merchant_key_store,
+ )
+ .await
+ }
+
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,