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
fix(storage): align kv helpers with intent insert path and build drainer queries lazily (#13172)
Hrithikesh6d555d8efc14
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rsindex f693d0e62f..0f8acaa8cd 100644--- a/crates/diesel_models/src/payment_intent.rs+++ b/crates/diesel_models/src/payment_intent.rs@@ -114,7 +114,17 @@ pub struct PaymentIntent {}#[cfg(feature = "v1")]-#[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)]+#[derive(+ Clone,+ Debug,+ PartialEq,+ Identifiable,+ Queryable,+ Serialize,+ Deserialize,+ Selectable,+ router_derive::FromNew,+)]#[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))]pub struct PaymentIntent {pub payment_id: common_utils::id_type::PaymentId,diff --git a/crates/diesel_models/src/query/address.rs b/crates/diesel_models/src/query/address.rsindex f7bb86cfbd..b7f057aa67 100644--- a/crates/diesel_models/src/query/address.rs+++ b/crates/diesel_models/src/query/address.rs@@ -1,4 +1,5 @@use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+use error_stack::ResultExt;use super::generics;use crate::{@@ -17,7 +18,9 @@ impl AddressNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for address")}}@@ -161,5 +164,6 @@ impl AddressUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for address")}}diff --git a/crates/diesel_models/src/query/authentication.rs b/crates/diesel_models/src/query/authentication.rsindex bb2edbb24a..95eeedbdc5 100644--- a/crates/diesel_models/src/query/authentication.rs+++ b/crates/diesel_models/src/query/authentication.rs@@ -1,4 +1,5 @@use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+use error_stack::ResultExt;use super::generics;use crate::{@@ -17,7 +18,9 @@ impl AuthenticationNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for authentication")}}@@ -176,5 +179,6 @@ impl AuthenticationUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for authentication")}}diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rsindex e7f33f4c3a..552f096bc8 100644--- a/crates/diesel_models/src/query/capture.rs+++ b/crates/diesel_models/src/query/capture.rs@@ -1,5 +1,6 @@use common_utils::types::ConnectorTransactionIdTrait;use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+use error_stack::ResultExt;use super::generics;use crate::{@@ -18,7 +19,9 @@ impl CaptureNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for capture")}}@@ -107,5 +110,6 @@ impl CaptureUpdate {CaptureUpdateInternal::from(self),).await+ .attach_printable("Failed to generate update query for capture")}}diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rsindex ca4f70c4d3..7e121bd518 100644--- a/crates/diesel_models/src/query/customers.rs+++ b/crates/diesel_models/src/query/customers.rs@@ -5,7 +5,8 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};#[cfg(feature = "v2")]use diesel::{NullableExpressionMethods, QueryDsl};#[cfg(feature = "v2")]-use error_stack::{report, ResultExt};+use error_stack::report;+use error_stack::ResultExt;use super::generics;#[cfg(feature = "v2")]@@ -28,7 +29,9 @@ impl CustomerNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for customer")}}@@ -423,6 +426,7 @@ impl CustomerUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for customer")}#[cfg(feature = "v2")]@@ -431,6 +435,8 @@ impl CustomerUpdateInternal {conn: &mut PgPooledConn,id: id_type::GlobalCustomerId,) -> StorageResult<kv::SerializableQuery> {- kv::generate_update_query_by_id::<<Customer as HasTable>::Table, _, _>(conn, id, self).await+ kv::generate_update_query_by_id::<<Customer as HasTable>::Table, _, _>(conn, id, self)+ .await+ .attach_printable("Failed to generate update query for customer")}}diff --git a/crates/diesel_models/src/query/dispute.rs b/crates/diesel_models/src/query/dispute.rsindex 3f5b151b37..ce4861e54f 100644--- a/crates/diesel_models/src/query/dispute.rs+++ b/crates/diesel_models/src/query/dispute.rs@@ -1,4 +1,5 @@use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};+use error_stack::ResultExt;use super::generics;use crate::{@@ -17,7 +18,9 @@ impl DisputeNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for dispute")}}@@ -166,5 +169,6 @@ impl DisputeUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for dispute")}}diff --git a/crates/diesel_models/src/query/mandate.rs b/crates/diesel_models/src/query/mandate.rsindex 3dd4365f9e..4b25d4baf5 100644--- a/crates/diesel_models/src/query/mandate.rs+++ b/crates/diesel_models/src/query/mandate.rs@@ -1,5 +1,5 @@use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};-use error_stack::report;+use error_stack::{report, ResultExt};use super::generics;use crate::{errors, kv, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult};@@ -13,7 +13,9 @@ impl MandateNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for mandate")}}@@ -127,5 +129,6 @@ impl MandateUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for mandate")}}diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rsindex 061763a5b4..62f02a3a7c 100644--- a/crates/diesel_models/src/query/payment_attempt.rs+++ b/crates/diesel_models/src/query/payment_attempt.rs@@ -34,7 +34,9 @@ impl PaymentAttemptNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for payment attempt")}}@@ -579,6 +581,7 @@ impl PaymentAttemptUpdate {.populate_derived_fields(source_payment_attempt),).await+ .attach_printable("Failed to generate update query for payment attempt")}}@@ -595,5 +598,6 @@ impl PaymentAttemptUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for payment attempt")}}diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rsindex f63ffba976..13490df697 100644--- a/crates/diesel_models/src/query/payment_intent.rs+++ b/crates/diesel_models/src/query/payment_intent.rs@@ -1,4 +1,5 @@use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+use error_stack::ResultExt;use super::generics;#[cfg(feature = "v1")]@@ -20,7 +21,9 @@ impl PaymentIntentNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for payment intent")}}@@ -174,6 +177,7 @@ impl payment_intent::PaymentIntentUpdate {payment_intent::PaymentIntentUpdateInternal::from(self),).await+ .attach_printable("Failed to generate update query for payment intent")}}@@ -186,5 +190,6 @@ impl payment_intent::PaymentIntentUpdateInternal {) -> StorageResult<kv::SerializableQuery> {kv::generate_update_query_by_id::<<PaymentIntent as HasTable>::Table, _, _>(conn, id, self).await+ .attach_printable("Failed to generate update query for payment intent")}}diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rsindex 200631d800..ea91bb228a 100644--- a/crates/diesel_models/src/query/payment_method.rs+++ b/crates/diesel_models/src/query/payment_method.rs@@ -26,7 +26,9 @@ impl PaymentMethodNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for payment method")}}@@ -403,6 +405,7 @@ impl payment_method::PaymentMethodUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for payment method")}#[cfg(feature = "v2")]@@ -417,5 +420,6 @@ impl payment_method::PaymentMethodUpdateInternal {self,).await+ .attach_printable("Failed to generate update query for payment method")}}diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rsindex a0b2015840..db01148920 100644--- a/crates/diesel_models/src/query/payout_attempt.rs+++ b/crates/diesel_models/src/query/payout_attempt.rs@@ -29,7 +29,9 @@ impl PayoutAttemptNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for payout attempt")}}@@ -283,5 +285,6 @@ impl PayoutAttemptUpdate {PayoutAttemptUpdateInternal::from(self),).await+ .attach_printable("Failed to generate update query for payout attempt")}}diff --git a/crates/diesel_models/src/query/payouts.rs b/crates/diesel_models/src/query/payouts.rsindex 904a974316..1aa45bea83 100644--- a/crates/diesel_models/src/query/payouts.rs+++ b/crates/diesel_models/src/query/payouts.rs@@ -23,7 +23,9 @@ impl PayoutsNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for payouts")}}impl Payouts {@@ -160,5 +162,6 @@ impl PayoutsUpdate {PayoutsUpdateInternal::from(self),).await+ .attach_printable("Failed to generate update query for payouts")}}diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rsindex f9e0ee8cd0..b764e90e4b 100644--- a/crates/diesel_models/src/query/refund.rs+++ b/crates/diesel_models/src/query/refund.rs@@ -1,4 +1,5 @@use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};+use error_stack::ResultExt;use super::generics;#[cfg(feature = "v1")]@@ -20,7 +21,9 @@ impl RefundNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for refund")}}@@ -309,6 +312,7 @@ impl RefundUpdate {RefundUpdateInternal::from(self),).await+ .attach_printable("Failed to generate update query for refund")}#[cfg(feature = "v2")]@@ -323,5 +327,6 @@ impl RefundUpdate {RefundUpdateInternal::from(self),).await+ .attach_printable("Failed to generate update query for refund")}}diff --git a/crates/diesel_models/src/query/reverse_lookup.rs b/crates/diesel_models/src/query/reverse_lookup.rsindex 0c8417561b..d216d1c754 100644--- a/crates/diesel_models/src/query/reverse_lookup.rs+++ b/crates/diesel_models/src/query/reverse_lookup.rs@@ -1,4 +1,5 @@use diesel::{associations::HasTable, ExpressionMethods};+use error_stack::ResultExt;use super::generics;use crate::{@@ -25,7 +26,9 @@ impl ReverseLookupNew {self,conn: &mut PgPooledConn,) -> StorageResult<kv::SerializableQuery> {- kv::generate_insert_query(conn, self).await+ kv::generate_insert_query(conn, self)+ .await+ .attach_printable("Failed to generate insert query for reverse lookup")}}impl ReverseLookup {diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rsindex c9bbb11518..e1fff32163 100644--- a/crates/router_derive/src/lib.rs+++ b/crates/router_derive/src/lib.rs@@ -864,6 +864,18 @@ pub fn validate_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStrea.into()}+/// Derives `From<{StructName}New>` for the struct by mapping fields with matching names.+///+/// Assumes the `New` type follows the `{StructName}New` naming convention.+#[proc_macro_derive(FromNew)]+pub fn from_new_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {+ let ast = syn::parse_macro_input!(input as syn::DeriveInput);++ macros::from_new_derive_inner(ast)+ .unwrap_or_else(|error| error.to_compile_error())+ .into()+}+/// Derives code to validate if `String` or `Option<String>` fields contain potential XSS or SQLi.////// This macro generates a `validate_xss_or_sqli(&self) -> Result<(), String>` method that checksdiff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rsindex d551de1ff3..74a9bdd66d 100644--- a/crates/router_derive/src/macros.rs+++ b/crates/router_derive/src/macros.rs@@ -1,6 +1,7 @@pub(crate) mod api_error;pub(crate) mod apply_changeset;pub(crate) mod diesel;+pub(crate) mod from_new;pub(crate) mod generate_permissions;pub(crate) mod generate_schema;pub(crate) mod misc;@@ -20,6 +21,7 @@ pub(crate) use self::{api_error::api_error_derive_inner,apply_changeset::apply_changeset_attribute,diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner},+ from_new::from_new_derive_inner,generate_permissions::generate_permissions_inner,generate_schema::polymorphic_macro_derive_inner,schema::validate_schema_derive,diff --git a/crates/router_derive/src/macros/from_new.rs b/crates/router_derive/src/macros/from_new.rsnew file mode 100644index 0000000000..3c10890abe--- /dev/null+++ b/crates/router_derive/src/macros/from_new.rs@@ -0,0 +1,59 @@+use proc_macro2::TokenStream;+use quote::quote;+use syn::{DeriveInput, Fields};++/// Generate an `impl From<EntityNew> for Entity` based on struct fields.+///+/// Assumes the convention:+/// - The target `New` type is `{StructName}New`.+/// - Both `Entity` and `EntityNew` share the same field names and compatible types.+pub fn from_new_derive_inner(input: DeriveInput) -> syn::Result<TokenStream> {+ let struct_name = &input.ident;+ let new_type_name = syn::Ident::new(&format!("{}New", struct_name), struct_name.span());++ let fields = match &input.data {+ syn::Data::Struct(data) => match &data.fields {+ Fields::Named(fields_named) => &fields_named.named,+ _ => {+ return Err(syn::Error::new_spanned(+ struct_name,+ "FromNew only supports structs with named fields",+ ))+ }+ },+ _ => {+ return Err(syn::Error::new_spanned(+ struct_name,+ "FromNew only supports structs",+ ))+ }+ };++ let field_assignments = fields+ .iter()+ .map(|field| {+ let field_name = field.ident.as_ref().ok_or_else(|| {+ syn::Error::new_spanned(field, "FromNew only supports named fields")+ })?;++ Ok(quote! {+ #field_name: new.#field_name+ })+ })+ .collect::<syn::Result<Vec<_>>>()?;++ let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();++ let expanded = quote! {+ #[automatically_derived]+ impl #impl_generics From<#new_type_name> for #struct_name #ty_generics #where_clause {+ fn from(new: #new_type_name) -> Self {+ Self {+ #(#field_assignments),*+ }+ }+ }+ };++ Ok(expanded)+}diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rsindex d85b65d6cd..f8594b7b7d 100644--- a/crates/storage_impl/src/customers.rs+++ b/crates/storage_impl/src/customers.rs@@ -206,15 +206,11 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet field = format!("cust_{}", customer_id.get_string_repr());let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = customer_update_internal- .generate_drainer_update_query(- &mut query_gen_conn,- customer_id.clone(),- merchant_id.clone(),- )- .await- .change_context(StorageError::KVError)- .attach_printable("Failed to generate customer update query")?;+ let drainer_query_fut = customer_update_internal.generate_drainer_update_query(+ &mut query_gen_conn,+ customer_id.clone(),+ merchant_id.clone(),+ );Box::pin(self.update_resource(key_store,@@ -227,7 +223,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt),updated_customer,kv_router_store::UpdateResourceParams {- drainer_query,+ drainer_query_fut,operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),},))@@ -358,12 +354,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt}let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = new_customer+ let drainer_query_fut = new_customer.clone()- .generate_drainer_insert_query(&mut query_gen_conn)- .await- .change_context(StorageError::KVError)- .attach_printable("Failed to generate customer insert query")?;+ .generate_drainer_insert_query(&mut query_gen_conn);Box::pin(self.insert_resource(key_store,@@ -371,7 +364,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStnew_customer.clone().insert(&conn),new_customer.clone().into(),kv_router_store::InsertResourceParams {- drainer_query,+ drainer_query_fut,reverse_lookups,identifier,key,@@ -410,12 +403,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet customer = new_customer.clone().into();let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = new_customer+ let drainer_query_fut = new_customer.clone()- .generate_drainer_insert_query(&mut query_gen_conn)- .await- .change_context(StorageError::KVError)- .attach_printable("Failed to generate customer insert query")?;+ .generate_drainer_insert_query(&mut query_gen_conn);Box::pin(self.insert_resource(key_store,@@ -423,7 +413,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStnew_customer.clone().insert(&conn),customer,kv_router_store::InsertResourceParams {- drainer_query,+ drainer_query_fut,reverse_lookups: vec![],identifier,key,@@ -590,12 +580,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet field = format!("cust_{}", id.get_string_repr());let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = customer_update_internal+ let drainer_query_fut = customer_update_internal.clone()- .generate_drainer_update_query(&mut query_gen_conn, id.clone())- .await- .change_context(StorageError::KVError)- .attach_printable("Failed to generate customer update query")?;+ .generate_drainer_update_query(&mut query_gen_conn, id.clone());Box::pin(self.update_resource(key_store,@@ -603,7 +590,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStdatabase_call,customer_update_internal.apply_changeset(customer.clone()),kv_router_store::UpdateResourceParams {- drainer_query,+ drainer_query_fut,operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),},))diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rsindex 03b49738d8..570ae2f8d2 100644--- a/crates/storage_impl/src/kv_router_store.rs+++ b/crates/storage_impl/src/kv_router_store.rs@@ -60,8 +60,11 @@ impl<T: DatabaseStore> KVRouterStore<T> {}}-pub struct InsertResourceParams<'a> {- pub drainer_query: kv::SerializableQuery,+pub struct InsertResourceParams<'a, DrainerQueryFut>+where+ DrainerQueryFut: futures::Future<Output = diesel_models::StorageResult<kv::SerializableQuery>>,+{+ pub drainer_query_fut: DrainerQueryFut,pub reverse_lookups: Vec<String>,pub key: PartitionKey<'a>,// secondary key@@ -70,8 +73,11 @@ pub struct InsertResourceParams<'a> {pub resource_type: &'static str,}-pub struct UpdateResourceParams<'a> {- pub drainer_query: kv::SerializableQuery,+pub struct UpdateResourceParams<'a, DrainerQueryFut>+where+ DrainerQueryFut: futures::Future<Output = diesel_models::StorageResult<kv::SerializableQuery>>,+{+ pub drainer_query_fut: DrainerQueryFut,pub operation: Op<'a>,}@@ -385,24 +391,26 @@ impl<T: DatabaseStore> KVRouterStore<T> {}}- pub async fn insert_resource<D, R, M>(+ pub async fn insert_resource<D, R, M, DrainerQueryFut>(&self,key_store: &MerchantKeyStore,storage_scheme: MerchantStorageScheme,create_resource_fut: R,resource_new: M,InsertResourceParams {- drainer_query,+ drainer_query_fut,reverse_lookups,key,identifier,resource_type,- }: InsertResourceParams<'_>,+ }: InsertResourceParams<'_, DrainerQueryFut>,) -> error_stack::Result<D, errors::StorageError>whereD: Debug + Sync + Conversion,M: StorageModel<D>,R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,+ DrainerQueryFut:+ futures::Future<Output = diesel_models::StorageResult<kv::SerializableQuery>> + Send,{let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(self,@@ -430,6 +438,11 @@ impl<T: DatabaseStore> KVRouterStore<T> {futures::future::try_join_all(results).await?;+ let drainer_query = drainer_query_fut+ .await+ .change_context(errors::StorageError::KVError)+ .attach_printable("Failed to generate drainer insert query")?;+match Box::pin(kv_wrapper::<M, _, _>(self,KvOperation::<M>::HSetNx(&identifier, &resource_new, drainer_query),@@ -459,21 +472,23 @@ impl<T: DatabaseStore> KVRouterStore<T> {.change_context(errors::StorageError::DecryptionError)}- pub async fn update_resource<D, R, M>(+ pub async fn update_resource<D, R, M, DrainerQueryFut>(&self,key_store: &MerchantKeyStore,storage_scheme: MerchantStorageScheme,update_resource_fut: R,updated_resource: M,UpdateResourceParams {- drainer_query,+ drainer_query_fut,operation,- }: UpdateResourceParams<'_>,+ }: UpdateResourceParams<'_, DrainerQueryFut>,) -> error_stack::Result<D, errors::StorageError>whereD: Debug + Sync + Conversion,M: StorageModel<D>,R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,+ DrainerQueryFut:+ futures::Future<Output = diesel_models::StorageResult<kv::SerializableQuery>> + Send,{match operation {Op::Update(key, field, updated_by) => {@@ -494,6 +509,10 @@ impl<T: DatabaseStore> KVRouterStore<T> {let key_str = key.to_string();let redis_value = serde_json::to_string(&updated_resource).change_context(errors::StorageError::SerializationFailed)?;+ let drainer_query = drainer_query_fut+ .await+ .change_context(errors::StorageError::KVError)+ .attach_printable("Failed to generate drainer update query")?;Box::pin(kv_wrapper::<(), _, _>(self,diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rsindex 9fd6f3f8e3..9cbfb3471c 100644--- a/crates/storage_impl/src/payment_method.rs+++ b/crates/storage_impl/src/payment_method.rs@@ -187,12 +187,9 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {let payment_method = (&payment_method_new.clone()).into();let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = payment_method_new+ let drainer_query_fut = payment_method_new.clone()- .generate_drainer_insert_query(&mut query_gen_conn)- .await- .change_context(errors::StorageError::KVError)- .attach_printable("Failed to generate payment method insert query")?;+ .generate_drainer_insert_query(&mut query_gen_conn);let payment_method: DomainPaymentMethod = Box::pin(self.insert_resource(key_store,@@ -200,7 +197,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {payment_method_new.clone().insert(&conn),payment_method,InsertResourceParams {- drainer_query,+ drainer_query_fut,reverse_lookups,key,identifier,@@ -243,15 +240,10 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone());let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = p_update- .clone()- .generate_drainer_update_query(- &mut query_gen_conn,- payment_method.payment_method_id.clone(),- )- .await- .change_context(errors::StorageError::KVError)- .attach_printable("Failed to generate payment method update query")?;+ let drainer_query_fut = p_update.clone().generate_drainer_update_query(+ &mut query_gen_conn,+ payment_method.payment_method_id.clone(),+ );let payment_method: DomainPaymentMethod = Box::pin(self.update_resource(@@ -262,7 +254,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {.update_with_payment_method_id(&conn, p_update.clone()),updated_payment_method,UpdateResourceParams {- drainer_query,+ drainer_query_fut,operation: Op::Update(key.clone(),&field,diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rsindex f7036a93aa..3f702b7e99 100644--- a/crates/storage_impl/src/payments/payment_attempt.rs+++ b/crates/storage_impl/src/payments/payment_attempt.rs@@ -1160,11 +1160,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {.update_with_attempt_id(&conn, payment_attempt_internal.clone());let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = payment_attempt_internal- .generate_drainer_update_query(&mut query_gen_conn, payment_attempt.id.clone())- .await- .change_context(errors::StorageError::KVError)- .attach_printable("Failed to generate payment attempt update query")?;+ let drainer_query_fut = payment_attempt_internal+ .generate_drainer_update_query(&mut query_gen_conn, payment_attempt.id.clone());Box::pin(self.update_resource(merchant_key_store,@@ -1172,7 +1169,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {updated_payment_attempt_with_id,updated_payment_attempt,UpdateResourceParams {- drainer_query,+ drainer_query_fut,operation: Op::Update(key.clone(), &field, Some(updated_by.as_str())),},))diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rsindex 08af526cdb..205f307fe4 100644--- a/crates/storage_impl/src/payments/payment_intent.rs+++ b/crates/storage_impl/src/payments/payment_intent.rs@@ -2,9 +2,9 @@use api_models::payments::{AmountFilter, Order, SortBy, SortOn};#[cfg(feature = "olap")]use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};-use common_utils::ext_traits::{AsyncExt, Encode};+use common_utils::ext_traits::AsyncExt;#[cfg(feature = "v2")]-use common_utils::fallback_reverse_lookup_not_found;+use common_utils::{ext_traits::Encode, fallback_reverse_lookup_not_found};#[cfg(feature = "olap")]use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};#[cfg(feature = "v1")]@@ -43,6 +43,7 @@ use hyperswitch_domain_models::{PaymentIntent,},};+#[cfg(feature = "v2")]use redis_interface::HsetnxReply;#[cfg(feature = "olap")]use router_env::logger;@@ -50,16 +51,24 @@ use router_env::{instrument, tracing};#[cfg(feature = "olap")]use crate::connection;+#[cfg(feature = "v1")]+use crate::kv_router_store::{FindResourceBy, InsertResourceParams, UpdateResourceParams};use crate::{diesel_error_to_data_error,- errors::{RedisErrorExt, StorageError},+ errors::StorageError,kv_router_store::KVRouterStore,- redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},- utils::{self, pg_connection_read, pg_connection_write},+ redis::kv_store::{Op, PartitionKey},+ utils::{pg_connection_read, pg_connection_write},DatabaseStore,};#[cfg(feature = "v2")]use crate::{errors, lookup::ReverseLookupInterface};+#[cfg(feature = "v2")]+use crate::{+ errors::RedisErrorExt,+ redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation},+ utils,+};#[async_trait::async_trait]impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {@@ -78,63 +87,33 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {merchant_id: &processor_merchant_id,payment_id: &payment_id,};- let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(- self,- storage_scheme,- Op::Insert,- ))- .await;- match storage_scheme {- MerchantStorageScheme::PostgresOnly => {- self.router_store- .insert_payment_intent(payment_intent, merchant_key_store, storage_scheme)- .await- }-- MerchantStorageScheme::RedisKv => {- let key_str = key.to_string();- let new_payment_intent = payment_intent- .clone()- .construct_new()- .await- .change_context(StorageError::EncryptionError)?;- let diesel_payment_intent = payment_intent- .clone()- .convert()- .await- .change_context(StorageError::EncryptionError)?;+ let conn = pg_connection_write(self).await?;+ let new_payment_intent = payment_intent+ .construct_new()+ .await+ .change_context(StorageError::EncryptionError)?;+ let diesel_payment_intent = DieselPaymentIntent::from(new_payment_intent.clone());- let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = new_payment_intent- .generate_drainer_insert_query(&mut query_gen_conn)- .await- .change_context(StorageError::KVError)- .attach_printable("Failed to generate payment intent insert query")?;+ let mut query_gen_conn = pg_connection_write(self).await?;+ let drainer_query_fut = new_payment_intent+ .clone()+ .generate_drainer_insert_query(&mut query_gen_conn);- match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(- self,- KvOperation::<DieselPaymentIntent>::HSetNx(- &field,- &diesel_payment_intent,- drainer_query,- ),- key,- ))- .await- .map_err(|err| err.to_redis_failed_response(&key_str))?- .try_into_hsetnx()- {- Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue {- entity: "payment_intent",- key: Some(key_str),- }- .into()),- Ok(HsetnxReply::KeySet) => Ok(payment_intent),- Err(error) => Err(error.change_context(StorageError::KVError)),- }- }- }+ Box::pin(self.insert_resource(+ merchant_key_store,+ storage_scheme,+ new_payment_intent.insert(&conn),+ diesel_payment_intent,+ InsertResourceParams {+ drainer_query_fut,+ reverse_lookups: vec![],+ key,+ identifier: field,+ resource_type: "payment_intent",+ },+ ))+ .await}#[cfg(feature = "v2")]@@ -247,80 +226,40 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {) -> error_stack::Result<PaymentIntent, StorageError> {let processor_merchant_id = this.processor_merchant_id.clone();let payment_id = this.get_id().to_owned();+ let updated_by = this.updated_by.clone();let key = PartitionKey::MerchantIdPaymentId {merchant_id: &processor_merchant_id,payment_id: &payment_id,};let field = format!("pi_{}", this.get_id().get_string_repr());- let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(- self,+ let conn = pg_connection_write(self).await?;+ let diesel_intent_update = DieselPaymentIntentUpdate::from(payment_intent_update);+ let origin_diesel_intent = this+ .convert()+ .await+ .change_context(StorageError::EncryptionError)?;+ let diesel_intent = diesel_intent_update+ .clone()+ .apply_changeset(origin_diesel_intent.clone());++ let mut query_gen_conn = pg_connection_write(self).await?;+ let drainer_query_fut = diesel_intent_update.clone().generate_drainer_update_query(+ &mut query_gen_conn,+ origin_diesel_intent.payment_id.clone(),+ origin_diesel_intent.processor_merchant_id.clone(),+ );++ Box::pin(self.update_resource(+ merchant_key_store,storage_scheme,- Op::Update(key.clone(), &field, Some(&this.updated_by)),+ origin_diesel_intent.update(&conn, diesel_intent_update),+ diesel_intent,+ UpdateResourceParams {+ drainer_query_fut,+ operation: Op::Update(key.clone(), &field, Some(updated_by.as_str())),+ },))- .await;- match storage_scheme {- MerchantStorageScheme::PostgresOnly => {- self.router_store- .update_payment_intent(- this,- payment_intent_update,- merchant_key_store,- storage_scheme,- )- .await- }- MerchantStorageScheme::RedisKv => {- let key_str = key.to_string();-- let diesel_intent_update = DieselPaymentIntentUpdate::from(payment_intent_update);- let origin_diesel_intent = this- .convert()- .await- .change_context(StorageError::EncryptionError)?;-- let diesel_intent = diesel_intent_update- .clone()- .apply_changeset(origin_diesel_intent.clone());- // Check for database presence as well Maybe use a read replica here ?-- let redis_value = diesel_intent- .encode_to_string_of_json()- .change_context(StorageError::SerializationFailed)?;-- let mut query_gen_conn = pg_connection_write(self).await?;- let drainer_query = diesel_intent_update- .generate_drainer_update_query(- &mut query_gen_conn,- origin_diesel_intent.payment_id.clone(),- origin_diesel_intent.processor_merchant_id.clone(),- )- .await- .change_context(StorageError::KVError)- .attach_printable("Failed to generate payment intent update query")?;-- Box::pin(kv_wrapper::<(), _, _>(- self,- KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), drainer_query),- key,- ))- .await- .map_err(|err| err.to_redis_failed_response(&key_str))?- .try_into_hset()- .change_context(StorageError::KVError)?;-- let payment_intent = PaymentIntent::convert_back(- self.get_keymanager_state()- .attach_printable("Missing KeyManagerState")?,- diesel_intent,- merchant_key_store.key.get_inner(),- processor_merchant_id.into(),- )- .await- .change_context(StorageError::DecryptionError)?;-- Ok(payment_intent)- }- }+ .await}#[cfg(feature = "v2")]@@ -410,59 +349,24 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {merchant_key_store: &MerchantKeyStore,storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PaymentIntent, StorageError> {- let database_call = || async {- let conn = pg_connection_read(self).await?;+ let conn = pg_connection_read(self).await?;+ Box::pin(self.find_resource_by_id(+ merchant_key_store,+ storage_scheme,DieselPaymentIntent::find_by_payment_id_processor_merchant_id(&conn,payment_id,processor_merchant_id,- )- .await- .map_err(|er| {- let new_err = diesel_error_to_data_error(*er.current_context());- er.change_context(new_err)- })- };- let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(- self,- storage_scheme,- Op::Find,- ))- .await;- let diesel_payment_intent = match storage_scheme {- MerchantStorageScheme::PostgresOnly => database_call().await,-- MerchantStorageScheme::RedisKv => {- let key = PartitionKey::MerchantIdPaymentId {+ ),+ FindResourceBy::Id(+ payment_id.get_hash_key_for_kv_store(),+ PartitionKey::MerchantIdPaymentId {merchant_id: processor_merchant_id,payment_id,- };- let field = payment_id.get_hash_key_for_kv_store();- Box::pin(utils::try_redis_get_else_try_database_get(- async {- Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(- self,- KvOperation::<DieselPaymentIntent>::HGet(&field),- key,- ))- .await?- .try_into_hget()- },- database_call,- ))- .await- }- }?;-- PaymentIntent::convert_back(- self.get_keymanager_state()- .attach_printable("Missing KeyManagerState")?,- diesel_payment_intent,- merchant_key_store.key.get_inner(),- processor_merchant_id.to_owned().into(),- )+ },+ ),+ )).await- .change_context(StorageError::DecryptionError)}#[cfg(feature = "v2")]