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

refactor(webhook): event filtering to support separate query paths for event_id and object_id filters (#10402)

Venu Madhav Bandarupalli2196bfad37d0
diff --git a/crates/api_models/src/webhook_events.rs b/crates/api_models/src/webhook_events.rs
index 42a3010c2b..972ed159c5 100644
--- a/crates/api_models/src/webhook_events.rs
+++ b/crates/api_models/src/webhook_events.rs
@@ -56,6 +56,8 @@ pub enum EventListConstraintsInternal {
},
ObjectIdFilter {
object_id: String,
+ },
+ EventIdFilter {
event_id: String,
},
}
diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs
index f2283e17f3..5d9694ba3e 100644
--- a/crates/diesel_models/src/query/events.rs
+++ b/crates/diesel_models/src/query/events.rs
@@ -3,9 +3,11 @@ use std::collections::HashSet;
use diesel::{
associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods,
};
+use error_stack::ResultExt;
use super::generics;
use crate::{
+ errors::DatabaseError,
events::{Event, EventNew, EventUpdateInternal},
schema::events::dsl,
PgPooledConn, StorageResult,
@@ -46,11 +48,10 @@ impl Event {
.await
}
- pub async fn list_initial_attempts_by_merchant_id_primary_object_id_or_initial_attempt_id(
+ pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
- initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
@@ -58,11 +59,7 @@ impl Event {
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
- .and(
- dsl::primary_object_id
- .eq(primary_object_id.to_owned())
- .or(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
- ),
+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
@@ -70,6 +67,27 @@ impl Event {
.await
}
+ pub async fn find_initial_attempt_by_merchant_id_initial_attempt_id(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+ initial_attempt_id: &str,
+ ) -> StorageResult<Option<Self>> {
+ let predicate = dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::event_id.eq(initial_attempt_id.to_owned()));
+
+ let result =
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await;
+
+ match result {
+ Ok(event) => Ok(Some(event)),
+ Err(err) => match err.current_context() {
+ DatabaseError::NotFound => Ok(None),
+ _ => Err(err).attach_printable("Error finding event by initial_attempt_id"),
+ },
+ }
+ }
+
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_merchant_id_constraints(
conn: &PgPooledConn,
@@ -134,11 +152,10 @@ impl Event {
.await
}
- pub async fn list_initial_attempts_by_profile_id_primary_object_id_or_initial_attempt_id(
+ pub async fn list_initial_attempts_by_profile_id_primary_object_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
- initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
@@ -146,11 +163,7 @@ impl Event {
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::business_profile_id.eq(profile_id.to_owned()))
- .and(
- dsl::primary_object_id
- .eq(primary_object_id.to_owned())
- .or(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
- ),
+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
None,
None,
Some(dsl::created_at.desc()),
@@ -158,6 +171,27 @@ impl Event {
.await
}
+ pub async fn find_initial_attempt_by_profile_id_initial_attempt_id(
+ conn: &PgPooledConn,
+ profile_id: &common_utils::id_type::ProfileId,
+ initial_attempt_id: &str,
+ ) -> StorageResult<Option<Self>> {
+ let predicate = dsl::business_profile_id
+ .eq(profile_id.to_owned())
+ .and(dsl::event_id.eq(initial_attempt_id.to_owned()));
+
+ let result =
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await;
+
+ match result {
+ Ok(event) => Ok(Some(event)),
+ Err(err) => match err.current_context() {
+ DatabaseError::NotFound => Ok(None),
+ _ => Err(err).attach_printable("Error finding event by initial_attempt_id"),
+ },
+ }
+ }
+
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_profile_id_constraints(
conn: &PgPooledConn,
diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs
index 4a509c9247..deefb5d6b2 100644
--- a/crates/router/src/core/webhooks/webhook_events.rs
+++ b/crates/router/src/core/webhooks/webhook_events.rs
@@ -42,39 +42,62 @@ pub async fn list_initial_delivery_attempts(
(now.date() - time::Duration::days(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS)).midnight();
let (events, total_count) = match constraints {
- api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter {
- object_id,
- event_id,
- } => {
- let events =
- match account {
- MerchantAccountOrProfile::MerchantAccount(merchant_account) => store
- .list_initial_events_by_merchant_id_primary_object_or_initial_attempt_id(
+ api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => {
+ let events = match account {
+ MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
+ store
+ .list_initial_events_by_merchant_id_primary_object_id(
merchant_account.get_id(),
- &object_id,
- &event_id,
+ object_id.as_str(),
&key_store,
)
- .await,
- MerchantAccountOrProfile::Profile(business_profile) => {
- store
- .list_initial_events_by_profile_id_primary_object_or_initial_attempt_id(
- business_profile.get_id(),
- &object_id,
- &event_id,
- &key_store,
- )
- .await
- }
+ .await
}
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to list events with specified constraints")?;
+ MerchantAccountOrProfile::Profile(business_profile) => {
+ store
+ .list_initial_events_by_profile_id_primary_object_id(
+ business_profile.get_id(),
+ object_id.as_str(),
+ &key_store,
+ )
+ .await
+ }
+ }
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to list events with specified constraints")?;
let total_count = i64::try_from(events.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i64")?;
(events, total_count)
}
+ api_models::webhook_events::EventListConstraintsInternal::EventIdFilter { event_id } => {
+ let event_opt = match account {
+ MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
+ store
+ .find_initial_event_by_merchant_id_initial_attempt_id(
+ merchant_account.get_id(),
+ event_id.as_str(),
+ &key_store,
+ )
+ .await
+ }
+ MerchantAccountOrProfile::Profile(business_profile) => {
+ store
+ .find_initial_event_by_profile_id_initial_attempt_id(
+ business_profile.get_id(),
+ event_id.as_str(),
+ &key_store,
+ )
+ .await
+ }
+ }
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to find event with specified event_id")?;
+
+ let (events, total_count) = event_opt.map_or((vec![], 0), |event| (vec![event], 1));
+ (events, total_count)
+ }
api_models::webhook_events::EventListConstraintsInternal::GenericFilter {
created_after,
created_before,
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 9411743ea1..ae367ec1ce 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -2,6 +2,7 @@ use std::collections::HashSet;
use common_utils::ext_traits::AsyncExt;
use error_stack::{report, ResultExt};
+use futures::future::try_join_all;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
@@ -43,14 +44,6 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
- async fn list_initial_events_by_merchant_id_primary_object_or_initial_attempt_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- primary_object_id: &str,
- initial_attempt_id: &str,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
-
#[allow(clippy::too_many_arguments)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
@@ -71,14 +64,20 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
- async fn list_initial_events_by_profile_id_primary_object_or_initial_attempt_id(
+ async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
- profile_id: &common_utils::id_type::ProfileId,
+ merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
- initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+ async fn find_initial_event_by_merchant_id_initial_attempt_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError>;
+
#[allow(clippy::too_many_arguments)]
async fn list_initial_events_by_profile_id_constraints(
&self,
@@ -92,6 +91,20 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+ async fn list_initial_events_by_profile_id_primary_object_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ primary_object_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
+
+ async fn find_initial_event_by_profile_id_initial_attempt_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError>;
+
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -183,41 +196,6 @@ impl EventInterface for Store {
.change_context(errors::StorageError::DecryptionError)
}
- #[instrument(skip_all)]
- async fn list_initial_events_by_merchant_id_primary_object_or_initial_attempt_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- primary_object_id: &str,
- initial_attempt_id: &str,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- storage::Event::list_initial_attempts_by_merchant_id_primary_object_id_or_initial_attempt_id(
- &conn,
- merchant_id,
- primary_object_id,
- initial_attempt_id,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|events| async {
- let mut domain_events = Vec::with_capacity(events.len());
- for event in events.into_iter() {
- domain_events.push(
- event
- .convert(self.get_keymanager_state().attach_printable("Missing KeyManagerState")?,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- );
- }
- Ok(domain_events)
- })
- .await
- }
-
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
@@ -243,22 +221,18 @@ impl EventInterface for Store {
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|events| async {
- let mut domain_events = Vec::with_capacity(events.len());
- for event in events.into_iter() {
- domain_events.push(
- event
- .convert(
- self.get_keymanager_state()
- .attach_printable("Missing KeyManagerState")?,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- );
- }
- Ok(domain_events)
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async move {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
})
.await
}
@@ -278,47 +252,71 @@ impl EventInterface for Store {
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|events| async {
- let mut domain_events = Vec::with_capacity(events.len());
- for event in events.into_iter() {
- domain_events.push(
- event
- .convert(
- self.get_keymanager_state()
- .attach_printable("Missing KeyManagerState")?,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?,
- );
- }
- Ok(domain_events)
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async move {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
})
.await
}
#[instrument(skip_all)]
- async fn list_initial_events_by_profile_id_primary_object_or_initial_attempt_id(
+ async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
- profile_id: &common_utils::id_type::ProfileId,
+ merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
- initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- storage::Event::list_initial_attempts_by_profile_id_primary_object_id_or_initial_attempt_id(
+ storage::Event::list_initial_attempts_by_merchant_id_primary_object_id(
&conn,
- profile_id,
+ merchant_id,
primary_object_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async move {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
+ })
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_initial_event_by_merchant_id_initial_attempt_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::find_initial_attempt_by_merchant_id_initial_attempt_id(
+ &conn,
+ merchant_id,
initial_attempt_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|events| async {
- let mut domain_events = Vec::with_capacity(events.len());
- for event in events.into_iter() {
- domain_events.push(
+ .async_and_then(|event_opt| async {
+ match event_opt {
+ Some(event) => Ok(Some(
event
.convert(
self.get_keymanager_state()
@@ -328,9 +326,9 @@ impl EventInterface for Store {
)
.await
.change_context(errors::StorageError::DecryptionError)?,
- );
+ )),
+ None => Ok(None),
}
- Ok(domain_events)
})
.await
}
@@ -360,10 +358,73 @@ impl EventInterface for Store {
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
- .async_and_then(|events| async {
- let mut domain_events = Vec::with_capacity(events.len());
- for event in events.into_iter() {
- domain_events.push(
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async move {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ merchant_key_store.merchant_id.clone(),
+ ),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
+ })
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn list_initial_events_by_profile_id_primary_object_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ primary_object_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::list_initial_attempts_by_profile_id_primary_object_id(
+ &conn,
+ profile_id,
+ primary_object_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|events| {
+ try_join_all(events.into_iter().map(|event| async {
+ event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }))
+ })
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_initial_event_by_profile_id_initial_attempt_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Event::find_initial_attempt_by_profile_id_initial_attempt_id(
+ &conn,
+ profile_id,
+ initial_attempt_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ .async_and_then(|event_opt| async {
+ match event_opt {
+ Some(event) => Ok(Some(
event
.convert(
self.get_keymanager_state()
@@ -375,9 +436,9 @@ impl EventInterface for Store {
)
.await
.change_context(errors::StorageError::DecryptionError)?,
- );
+ )),
+ None => Ok(None),
}
- Ok(domain_events)
})
.await
}
@@ -518,43 +579,6 @@ impl EventInterface for MockDb {
)
}
- async fn list_initial_events_by_merchant_id_primary_object_or_initial_attempt_id(
- &self,
- merchant_id: &common_utils::id_type::MerchantId,
- primary_object_id: &str,
- initial_attempt_id: &str,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
- let locked_events = self.events.lock().await;
- let events = locked_events
- .iter()
- .filter(|event| {
- event.merchant_id == Some(merchant_id.to_owned())
- && event.initial_attempt_id.as_deref() == Some(&event.event_id)
- && (event.primary_object_id == primary_object_id
- || event.initial_attempt_id.as_deref() == Some(initial_attempt_id))
- })
- .cloned()
- .collect::<Vec<_>>();
-
- let mut domain_events = Vec::with_capacity(events.len());
-
- for event in events {
- let domain_event = event
- .convert(
- self.get_keymanager_state()
- .attach_printable("Missing KeyManagerState")?,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)?;
- domain_events.push(domain_event);
- }
-
- Ok(domain_events)
- }
-
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -656,21 +680,19 @@ impl EventInterface for MockDb {
Ok(domain_events)
}
- async fn list_initial_events_by_profile_id_primary_object_or_initial_attempt_id(
+ async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
- profile_id: &common_utils::id_type::ProfileId,
+ merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
- initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events = locked_events
.iter()
.filter(|event| {
- event.business_profile_id == Some(profile_id.to_owned())
- && event.initial_attempt_id.as_ref() == Some(&event.event_id)
- && (event.primary_object_id == primary_object_id
- || event.initial_attempt_id.as_deref() == Some(initial_attempt_id))
+ event.merchant_id == Some(merchant_id.to_owned())
+ && event.initial_attempt_id.as_deref() == Some(&event.event_id)
+ && event.primary_object_id.as_str() == primary_object_id
})
.cloned()
.collect::<Vec<_>>();
@@ -693,6 +715,37 @@ impl EventInterface for MockDb {
Ok(domain_events)
}
+ async fn find_initial_event_by_merchant_id_initial_attempt_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+
+ let event_opt = locked_events.iter().find(|event| {
+ event.merchant_id == Some(merchant_id.to_owned())
+ && event.event_id == initial_attempt_id
+ });
+
+ match event_opt {
+ Some(event) => {
+ let domain_event = event
+ .clone()
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ Ok(Some(domain_event))
+ }
+ None => Ok(None),
+ }
+ }
+
async fn list_initial_events_by_profile_id_constraints(
&self,
profile_id: &common_utils::id_type::ProfileId,
@@ -761,6 +814,72 @@ impl EventInterface for MockDb {
Ok(domain_events)
}
+ async fn list_initial_events_by_profile_id_primary_object_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ primary_object_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+ let events = locked_events
+ .iter()
+ .filter(|event| {
+ event.business_profile_id == Some(profile_id.to_owned())
+ && event.initial_attempt_id.as_deref() == Some(&event.event_id)
+ && event.primary_object_id.as_str() == primary_object_id
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+
+ let mut domain_events = Vec::with_capacity(events.len());
+
+ for event in events {
+ let domain_event = event
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ domain_events.push(domain_event);
+ }
+
+ Ok(domain_events)
+ }
+
+ async fn find_initial_event_by_profile_id_initial_attempt_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError> {
+ let locked_events = self.events.lock().await;
+
+ let event_opt = locked_events.iter().find(|event| {
+ event.business_profile_id == Some(profile_id.to_owned())
+ && event.event_id == initial_attempt_id
+ });
+
+ match event_opt {
+ Some(event) => {
+ let domain_event = event
+ .clone()
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+ Ok(Some(domain_event))
+ }
+ None => Ok(None),
+ }
+ }
+
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
@@ -1294,7 +1413,6 @@ mod tests {
let event_type = enums::EventType::PaymentSucceeded;
let event_class = enums::EventClass::Payments;
let primary_object_id = Arc::new("concurrent_payment_id".to_string());
- let initial_attempt_id = Arc::new("initial_attempt_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",
@@ -1450,21 +1568,44 @@ mod tests {
}
// Collect all initial-attempt events for this payment
- let events = state
+ let events_by_object_id = state
.store
- .list_initial_events_by_merchant_id_primary_object_or_initial_attempt_id(
+ .list_initial_events_by_merchant_id_primary_object_id(
&business_profile.merchant_id,
- &primary_object_id.clone(),
- &initial_attempt_id.clone(),
- platform.get_processor().get_key_store(),
+ primary_object_id.as_str(),
+ &merchant_key_store,
)
.await?;
assert_eq!(
- events.len(),
+ events_by_object_id.len(),
1,
- "Expected exactly 1 row in events table, found {}",
- events.len()
+ "Expected exactly 1 row in events table when querying by primary_object_id, found {}",
+ events_by_object_id.len()
+ );
+
+ let first_event = events_by_object_id
+ .first()
+ .ok_or("Expected at least one event in the result")?;
+ let event_id = first_event.event_id.clone();
+ let event_by_event_id = state
+ .store
+ .find_initial_event_by_merchant_id_initial_attempt_id(
+ &business_profile.merchant_id,
+ &event_id,
+ &merchant_key_store,
+ )
+ .await?;
+
+ assert!(
+ event_by_event_id.is_some(),
+ "Expected to find an event when querying by initial_attempt_id (event_id)"
+ );
+
+ let found_event = event_by_event_id.unwrap();
+ assert_eq!(
+ first_event.event_id, found_event.event_id,
+ "Event IDs should match between queries"
);
Ok(())
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index a085804317..24ad1e6f28 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -734,23 +734,6 @@ impl EventInterface for KafkaStore {
.await
}
- async fn list_initial_events_by_merchant_id_primary_object_or_initial_attempt_id(
- &self,
- merchant_id: &id_type::MerchantId,
- primary_object_id: &str,
- initial_attempt_id: &str,
- merchant_key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
- self.diesel_store
- .list_initial_events_by_merchant_id_primary_object_or_initial_attempt_id(
- merchant_id,
- primary_object_id,
- initial_attempt_id,
- merchant_key_store,
- )
- .await
- }
-
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &id_type::MerchantId,
@@ -791,17 +774,30 @@ impl EventInterface for KafkaStore {
.await
}
- async fn list_initial_events_by_profile_id_primary_object_or_initial_attempt_id(
+ async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
- profile_id: &id_type::ProfileId,
+ merchant_id: &id_type::MerchantId,
primary_object_id: &str,
- initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
- .list_initial_events_by_profile_id_primary_object_or_initial_attempt_id(
- profile_id,
+ .list_initial_events_by_merchant_id_primary_object_id(
+ merchant_id,
primary_object_id,
+ merchant_key_store,
+ )
+ .await
+ }
+
+ async fn find_initial_event_by_merchant_id_initial_attempt_id(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError> {
+ self.diesel_store
+ .find_initial_event_by_merchant_id_initial_attempt_id(
+ merchant_id,
initial_attempt_id,
merchant_key_store,
)
@@ -833,6 +829,36 @@ impl EventInterface for KafkaStore {
.await
}
+ async fn list_initial_events_by_profile_id_primary_object_id(
+ &self,
+ profile_id: &id_type::ProfileId,
+ primary_object_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
+ self.diesel_store
+ .list_initial_events_by_profile_id_primary_object_id(
+ profile_id,
+ primary_object_id,
+ merchant_key_store,
+ )
+ .await
+ }
+
+ async fn find_initial_event_by_profile_id_initial_attempt_id(
+ &self,
+ profile_id: &id_type::ProfileId,
+ initial_attempt_id: &str,
+ merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<Option<domain::Event>, errors::StorageError> {
+ self.diesel_store
+ .find_initial_event_by_profile_id_initial_attempt_id(
+ profile_id,
+ initial_attempt_id,
+ merchant_key_store,
+ )
+ .await
+ }
+
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &id_type::MerchantId,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index a56d17da5e..32a0b5c4eb 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1823,27 +1823,16 @@ impl ForeignTryFrom<api_types::webhook_events::EventListConstraints>
{
return Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
- "Either only `object_id` or `event_id` must be specified, or one or more of \
+ "Either `object_id` alone, or `event_id` alone, or one or more of \
`created_after`, `created_before`, `limit`, `offset`, `event_classes` and `event_types` must be specified"
.to_string()
}));
}
match (item.object_id.clone(), item.event_id.clone()) {
- (Some(object_id), Some(event_id)) => Ok(Self::ObjectIdFilter {
- object_id,
- event_id,
- }),
+ (Some(object_id), None) => Ok(Self::ObjectIdFilter { object_id }),
- (Some(object_id), None) => Ok(Self::ObjectIdFilter {
- event_id: object_id.clone(),
- object_id,
- }),
-
- (None, Some(event_id)) => Ok(Self::ObjectIdFilter {
- object_id: event_id.clone(),
- event_id,
- }),
+ (None, Some(event_id)) => Ok(Self::EventIdFilter { event_id }),
(None, None) => Ok(Self::GenericFilter {
created_after: item.created_after,
@@ -1854,6 +1843,11 @@ impl ForeignTryFrom<api_types::webhook_events::EventListConstraints>
event_types: item.event_types,
is_delivered: item.is_delivered,
}),
+
+ (Some(_), Some(_)) => Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Cannot specify both `object_id` and `event_id`. Please provide only one."
+ .to_string()
+ })),
}
}
}